2.Varibale
Varibale分两类:
- Primitive Data Types: 值类型传值时会将值拷贝一份,传递的是值本身,对其修改时并不会对原来值有影响。
- 始终按值来传递,当被用作函数参数或者用在赋值语句中时,总会进行值拷贝。
- 值类型里有两个比较特殊的类型是函数和地址(包括合约),会分为单独的部分介绍。
- 引用类型: 引用类型进行传递时,传递的是其指针,而引用类型进行传递时可以为值传递,也可以为引用传递。
值类型¶
- bool
- uint/int
- bytes
- address
- mapping
- enum
- struct
- bytes/String
- fixed
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract ValueTypes {
bool public b1 = true;
/*
unsign: 非负数
unint 默认unit256 0-2^256
unint8 0-2^8
unint16 0-2^16
*/
uint256 public u = 123;
/*
想用负数怎么办,int
int默认256 -2^255-2^255
int128 -2^127-2^127
*/
int256 public i = -123;
int256 public minInt = type(int256).min;
int256 public maxInt = type(int256).max;
address public addr = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;
/*
byte 表示a sequence of byte
表示形式有两种:
1. 大小固定的 byte array
2. 大小动态变化的 byte arrays
*/
bytes1 a = 0xb5; // [10110101]
bytes1 b = 0x56; // [01010110]
// Default values
// Unassigned variables have a default value
bool public defaultBoo; // false
uint256 public defaultUint; // 0
int256 public defaultInt; // 0
address public defaultAddr; // 0x0000000000000000000000000000000000000000
}
默认值
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract DefaultValues {
bool public b;// false
uint public u;// 0
int public i;// 0
address public a;// 0x0000000000000000000000000000000000000000
bytes32 public b32;//
// mapping, structs, enums, fixed sized arrays
}
更多
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract Primitives {
bool public boo = true;
/*
uint stands for unsigned integer, meaning non negative integers
different sizes are available
uint8 ranges from 0 to 2 ** 8 - 1
uint16 ranges from 0 to 2 ** 16 - 1
...
uint256 ranges from 0 to 2 ** 256 - 1
*/
uint8 public u8 = 1;
uint public u256 = 456;
uint public u = 123; // uint is an alias for uint256
/*
Negative numbers are allowed for int types.
Like uint, different ranges are available from int8 to int256
int256 ranges from -2 ** 255 to 2 ** 255 - 1
int128 ranges from -2 ** 127 to 2 ** 127 - 1
*/
int8 public i8 = -1;
int public i256 = 456;
int public i = -123; // int is same as int256
// minimum and maximum of int
int public minInt = type(int).min;
int public maxInt = type(int).max;
address public addr = 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c;
/*
In Solidity, the data type byte represent a sequence of bytes.
Solidity presents two type of bytes types :
- fixed-sized byte arrays
- dynamically-sized byte arrays.
The term bytes in Solidity represents a dynamic array of bytes.
Itâs a shorthand for byte[] .
*/
bytes1 a = 0xb5; // [10110101]
bytes1 b = 0x56; // [01010110]
// Default values
// Unassigned variables have a default value
bool public defaultBoo; // false
uint public defaultUint; // 0
int public defaultInt; // 0
address public defaultAddr; // 0x0000000000000000000000000000000000000000
}
引用类型¶
Solidity 中,有一些数据类型由值类型组合而成,相比于简单的值类型,这些类型通常通过名称引用,被称为引用类型。
- array
- string: 是一个动态尺寸的 utf-8 编码字符串
- bytes: 动态十六进制字节数组
- mapping
- struct