Solidity是强类型语言,每个变量必须在编译前制定其类型。大体分为值类型和引用类型
1. 值类型(始终按值传递的变量)
整型
有符号int8~int256 数字以8递进,
无符号uint8~uint256,
如:int8 data = 10
浮点型
有符号浮点型fixedMxN,
无符号浮点型ufixedMxN,
M表示该类型占用的位数,
N表示可用的小数
地址型
address,存储一个20字节的值,address x=0x768855
x.balance 用来返回x的地址余额
x.transfer表示向x地址发送以太币
x.sender是transfer的低级版本,执行合约失败不会因一场而终止,send只会返回false。这两种函数调用,默认消耗2300Gas
另外三种安全性低的函数x.call,x.callcode,x.delegatecall 在使用时需要小心谨慎。在没有对合约完全了解的时候不要随意使用
call 函数的调用默认所有的Gas都可用,可以返回成功状态和数据
布尔型
条件判断 bool isOwner = true
定长字节数组
byte1~byte32 按照1来递进,
在内存开辟固定的空间,byte3 tom = “tom”
与String区别,String可以看作是变长数组,消耗的Gas会比byte32类型多,因此字符串长度已知,使用byte32会更节省内存
字面常量
地址,字符串,整数等字面常数
枚举类型
Solidity自定义类型,表示枚举类型
enum Number{integer,float}
2. 引用类型
结构类型:
通过定义一个结构体定义新的类型 struct xxx {...}
映射:
mapping(Keytype => Valuetype)
mapping(address => int )用来映射某个地址存储的代币
数组:
包括定长数组和动态数组Type[length]和Type[],如: uint[4] array={1,2,3,4}
3. 函数定义
定义一个函数的标准格式
internal/external pure/constant/view/payable return(返回值类型){函数体}
internal表示智能在当前合约内部使用,external表述函数可以被外部的合约调用
只读取,没有任何更改可以用view
// SPDX-License-Identifier: MIT
// comment: this is my first smart contract
pragma solidity ^0.8.30;
contract HelloWorld{
string strVal = "Hello World";
function sayHello() public view returns(string memory) {
return strVal;
}
function setHelloWorld(string memory newString) public {
strVal = newString;
}
}
pure:代表纯函数
4.数据存储位置
memeory,
空间小存储形式为字节数组,仅用于保存临时变量,函数返回值默认在memory和参数,
运行时候可以修改
storage,
空间相对较大,存储形式为key value,合约的状态默认存储在storage,
永久存储
calldata,
calldata 用来存储函数的参数,是只读、不能永久保存,外部函数的参数被强制存储在calldata,
运行时不能修改
logs,
stack,
codes
5. 数据结构
mapping,
array,
struct
6.引入其他合约
import {HelloWorld} from "./test.sol";
直接本地文件,
import { 合约 } from URI
通过网络,
import { 合约 } from “@companyName/product/contract” 「类似npm」
通过引入包的方式