了解值类型

在本单元中,你将了解 Solidity 中的主要值类型。 值类型通过值传递,并在使用时进行复制。 编写合同时将使用的主要值类型包括“整数”、“布尔”、“string literal”、“地址”和“枚举”。

整数

每个 Solidity 源文件中都使用整数。 它们表示整数,可以有符号也可以无符号。 存储的整数大小介于 8 位到 256 位之间。

  • 已签名:包括负数和正数。 可以表示为 int。
  • 未签名:仅包含正数。 可以表示为 uint。

如果未指定位数,则默认值为 256 位。

以下操作可应用于整数:

  • 比较:<=<==!=>=>
  • 位运算符:& (and)| (or)^ (bitwise exclusive)~ (bitwise negation)
  • 算术运算符:+ (addition)- (subtraction)* (multiplication)/ (division)% (modulo)** (exponential)

以下是整数定义的一些示例:

int32 price = 25; // signed 32 bit integer
uint256 balance = 1000; // unsigned 256 bit integer

balance - price; // 975
2 * price; // 50
price % 2; // 1

布尔型

布尔使用关键字 bool 进行定义。 它们的值始终是 true 或 false

下面提供了定义方法:

bool forSale; //true if an item is for sale
bool purchased; //true if an item has been purchased

布尔通常用于比较语句中。 例如:

if(balance > 0 & balance > price) {
    return true;
}

if(price > balance) {
    return false;
}

布尔也可以用在函数参数和返回类型中。

function buy(int price) returns (bool success) {
    // ...
}

字符串文本

大多数合同文件中也使用 String literals。 它们是用双引号或单引号括起来的字符或字词。

    String shipped = "shipped"; // shipped
    String delivered = 'delivered'; // delivered
    String newItem = "newItem"; // newItem

此外,以下转义字符可以与 string literals 一起使用。

  • \<newline> 转义为换行
  • \n 换行
  • \r 回车
  • \t Tab

地址

地址是一种具有 20 字节值的类型,它表示 Ethereum 用户帐户。 此类型可以是常规“address”,也可以是“address payable”。

两者之间的区别在于,“address payable”类型是 Ether 发送到的地址,它包含额外的成员 transfer 和 send

address payable public seller; // account for the seller
address payable public buyer; // account for the user

function transfer(address buyer, uint price) {
    buyer.transfer(price); // the transfer member transfers the price of the item
}

枚举

在 Solidity 中,可使用枚举创建用户定义类型。 之所以称之为用户定义,是因为创建合同的人员决定要包含哪些值。 枚举可用于显示许多可选择的选项,其中有一项是必需的。

例如,可以使用 enum 来表示项目的不同状态。 可以将枚举视为代表多项选择答案,其中所有值都是预定义的,你必须选择一个。 可以在合同或库定义中声明枚举。

enum Status { 
    Pending,
    Shipped,
    Delivered 
}

Status public status;

constructor() public {
    status = Status.Pending;
}
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值