在 Solidity 中,数据类型是构建智能合约的基础。理解不同的数据类型对于编写安全和高效的智能合约至关重要。
基本数据类型
以下是 Solidity 中的一些基本数据类型:
- 布尔型 (bool): 表示真或假的值。
- 字节型 (bytes): 字节序列,可以存储任意长度的数据。
- 整数型 (int): 有符号整数,包括
int8
到int256
。 - 无符号整数型 (uint): 无符号整数,包括
uint8
到uint256
。 - 固定大小字节型 (bytes32): 固定大小的字节序列,总是32字节。
复杂数据类型
- 数组 (array): 元素集合,可以是固定大小的或动态大小的。
- 结构体 (struct): 类似于类,可以包含多个字段。
- 映射 (mapping): 键值对集合,键可以是任何数据类型。
示例
以下是一个使用 Solidity 数据类型的简单示例:
pragma solidity ^0.8.0;
contract DataTypesExample {
bool public isContractActive = true;
uint public balance = 100;
string public name = "Solidity Data Types";
// 使用数组
uint[] public numbers = [1, 2, 3, 4, 5];
// 使用结构体
struct Person {
string name;
uint age;
}
Person public person = Person("Alice", 30);
// 使用映射
mapping(uint => string) public names;
function addPerson(uint id, string memory name) public {
names[id] = name;
}
}
扩展阅读
想要了解更多关于 Solidity 数据类型的信息?请访问我们的数据类型详解页面。
[center]https://cloud-image.ullrai.com/q/Solidity_Logo/[/center]