Solidity中的变量类型
数值类型 Value Type
此类变量赋值时直接传递数值:布尔型、整数型……
引用类型 Reference Type
此类变量占空间大,赋值时直接传递地址(类似指针):数组array、结构体struct
映射类型 Mapping Type
solidity中的哈希表
函数类型 Function Type
solidity文档中将函数类型归为数值类型(课程作者认为其差别较大故单独分类)
数组 array
定义:
用来存储一组数据(整数、字节、地址等等)
分为:
- 固定长度数组:在声明时指定数组的长度,用**T[K]**的格式声明,T为元素类型,K为长度
复制代码
1
2
3
4
5// 固定长度Array uint[8] array1; bytes1[5] array2; address[100] array3;
2. 可变长度数组(动态数组):在声明时不指定数组的长度,用T[ ]格式声明,T为元素类型 (bytes比较特殊,是数组,但不用加[ ])
复制代码
1
2
3
4
5
6// 可变长度 Array uint[] array4; bytes1[] array5; address[] array6; bytes array7;
创建数组的规则
- memory修饰的动态数组:可用new操作符来创建,但必须声明长度,且声明后长度不能改变
复制代码
1
2
3
4// memory动态数组 uint[] memory array8 = new uint[](5); bytes memory array9 = new bytes(9);
2. 数组字面常数Array Literals:写作表达式形式的数组,用方括号包着来初始化array的一种方式,且里面每一个元素的type是以第一个元素为准
——如: [1,2,3]里面所有的元素都是uint8类型,因为solidity中如果一个值没有指定type的话,默认就是最小单位的该type,这里int的默认最小单位类型就是uint8
——接上文: [unit (1),2,3]里面的元素都是uint类型,因为第一个元素指定是uint类型,所有都以第一个元素为准
——下面的合约中:对于 f 函数里面的调用,如果没有显示对第一个元素进行uint强行转化的话,会报错。因为如上所述,我们其实是转入了uint8类型的array,可是 g 函数需要的却是uint类型的array,就会报错了
复制代码
1
2
3
4
5
6
7
8
9
10// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.4.16 <0.9.0; contract C { function f() public pure { g([uint(1),2,3]); } function g(uint[3] memory) public pure { } }
3. 创建动态数组:需要一个一个元素的赋值
复制代码
1
2
3
4
5uint【】 memory x = new uint[](3); x[0] = 1; x[1] = 3; x[2] = 4;
数组成员
- length:包含元素数量:数组有length,memory数组的长度在创建后固定
- push () :动态数组和bytes有push(),可以在数组最后添加一个0元素
- push(x):动态数组和bytes有push(x),可以在数组最后添加一个x元素
- pop () :动态数组和bytes有pop(),可以移除数组最后一个元素
结构体 struct
- solidity支持通过构造结构体的形式定义新的类型
复制代码
1
2
3
4
5
6// 创建结构体 struct Student{ uint256 id; uint256 score; }
复制代码
1
2Student student; //初始一个student结构体
2. 给结构体赋值的两种方法
复制代码
1
2
3
4
5
6
7
8// 给结构体赋值 // **方法1:在函数中创建一个storage的struct引用** function initStudent1() external{ Student storage _student = student; // assign a copy of student _student.id = 11; _student.score = 100; }
复制代码
1
2
3
4
5
6// **方法2:直接引用状态变量struct** function initStudent2() external{ student.id = 1; student.score = 80; }
最后
以上就是踏实心情最近收集整理的关于【solidity入门】5. 引用类型 Reference Type的全部内容,更多相关【solidity入门】5.内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复