本教材由知了传课辛苦制作而成,仅供学习使用,请勿用于商业用途!如进行转载请务必注明出处!谢谢!

solidity–数据类型

一、值类型

1.布尔类型(Booleans):true或false,默认是false

  • !逻辑非
  • && 逻辑与
  • || 逻辑或
  • == 等于
  • != 不等于
pragma solidity 0.4.24; contract DataType { // bool public ok = true; bool public ok; // 默认是false function test() returns(string){ if (ok) { return "这是true"; }else { return "这false"; } } }

2.整型(Integers):int/uint: 表示有符号和无符号不同位数整数

  • 以8位为区间,有int8,int16,int24,…,int256,int默认是int256,uint同理
int8 num; int256 total = 120; 举例:两个数相加的结果 pragma solidity ^0.4.24; contract Add { int8 i1 = 10; int16 i2 = 11; function add() returns (int8){ return i1 + int8(i2); // 类型强转 } }

3.定长浮点型(Fixed Point Numbers):fixed/ufixed: 表示有符号和无符号的固定位浮点数

  • 还不完全支持,它可以用来声明变量,但不可以用来赋值

4.定长字节数组(Fixed-size byte arrays)

  • 关键字有:bytes1, bytes2, bytes3, …, bytes32。
  • byte 代表 bytes1。bytes1存储1个字节,即8位,bytes2存储2个字节,步长为1字节递增
  • .length:表示这个字节数组的长度(只读),返回的是定长字节数组类型的长度,而不是值的长度
  • 长度不能修改
  • 可以通过下标获取
  • 元素值不可修改,只读
pragma solidity 0.4.24; contract TestBytes { // bytes1 public b1; // 字节:0x00 bytes1 public b1 = "h"; // 0x68 bytes2 public b2 = "hh"; // 0x6868 bytes6 public b6 = "hallen"; // 0x68616c6c656e bytes32 public b32 = "hallen"; function get_len() returns(int256){ return b32.length; } function get_by_index() returns(bytes1){ return b1[0]; } }

5.有理数和整型常量(Rational and Integer Literals)

  • 表达式中直接出现的数字常量:整数,小数,科学计数都支持(2e20:2*10^20)

6.枚举(Enums)

  • 自定义类型
  • 至少要有一个元素,默认位uint8
  • enum Gender { Male, FeMale }
  • 不要忘了花括号
enum Gender { Male, FeMale } Gender default = Gender.Male // Gender为自定义类型,设置默认值

7.函数类型(Function Types)

8.地址类型(Address)

二、引用类型

1.字符串

  • 不支持索引
  • 不支持length和push方法
  • 可以修改,需要通过bytes转换
string name = "hallen"; // 转bytes,然后就可以使用bytes的特性了 bytes(name).length; // bytes转string string(bytes)

2.不定长字节数组:bytes

  • 支持length,push(在最后追加)方法
  • 可以修改
  • 支持索引,如果未分配空间(new分配空间),使用下标会报角标越界,其他的会自动分配空间
  • 以十六进制格式赋值
bytes name = "hallen" name.push("a")

3.数组

  • 内置数组:string、bytes、bytes1…bytes32
  • 自定义定长数组:长度不可变,支持length,不支持push
uint256[5] public nums = [1,2,3,4,5];
  • 自定义不定长数组:长度可变,内容可修改,支持length,push方法
uint256[] public nums = [1,2,3,4,5]; nums.push(6) delete nums; // 函数中使用new分配空间 uint8[] memory aa = new uint8[](10);// 10个长度的空间

4.结构体:函数不支持返回结构体对象,可以把值放到元组中返回(按个放到()中,返回元组)

struct 结构体名称{ 类型 字段名; } struct Person { string name; uint age; } // 指定字段名,必须用()括起来,里面是花括号 Person public p1 = Person({name:"hallen",age:18}); // 按顺序初始化值,注意是括号()不是花括号{} Person public p2 = Person("hallen",18); // 结构体不定长数组 Person[] persons; // 函数中可以往里面添加值,类型必须是结构体初始化对象 persons.push(p1);

5.mapping:映射,

  • 无法判断是否存在某个key
  • 不支持length
mapping(string=>string) map_data; // 函数中赋值 map_data["name"] = "hallen"; //获取指定的key的值 string storage aa = map_data["name"];

三、storage和memory

storage:数据永远保存,引用传递,只有引用类型的变量才可以显示的声明为storage。

memory:存在内存中,会被回收,数据会过期丢失,类似值类型

四、bytes1、bytes、string相互转换

bytes1转string要经过中间的bytes

角标用uint256类型,不然会类型不匹配

1589人已阅读,今天你学习了吗?

添加新回复