了解Solidity中的数据结构和控制结构

342 阅读3分钟

读者你好,你知道什么是数据结构吗?如果不知道,那么下面就是数据结构的含义。

数据结构是在计算机内存中组织数据的一种特殊方式,以便它能被有效地使用。

Solidity提供三种类型的数据结构

  1. 结构
  2. 数组
  3. 映射

Solidity Data StructuresSolidity Data Structures

Solidity 数据结构

让我们一个接一个地看一下每个数据结构。

结构

Solidity 提供了一种方法来定义结构形式的新类型。结构是一种特殊的数据类型,允许程序员对变量列表进行分组。

pragma solidity ^0.4.0;
contract Ballot {
struct Voter { // Struct
uint weight1, weight2, weight3;
bool voted;
address delegate1, delegate2, delegate3, delegate4;
string name;
uint vote1, vote2, vote3, vote4, vote5;
uint height1, height2, height3   } }

结构允许您创建具有多个属性的更复杂的数据类型。

结构只能有16个成员,超过后可能会出现以下错误。堆栈太深。

数组

现在,如果你需要一个东西的集合,比如说地址。嗯,就像大多数语言一样,Solidity也有数组。

当你想要一个东西的集合时,你可以使用一个数组。在 Solidity 中有两种类型的数组:固定数组和动态数组。

数组有固定长度的2个元素,包含整数。
uint[2] fixedArray;

另一个固定数组,可以包含5个字符串。 string[5] stringArray;

一个动态数组 - 没有固定的大小,可以不断增长。
uint[] dynamicArray;

一个结构的数组:
StructName[] variablename;

使用结构体和数组工作


考虑一下我们之前创建的结构体

struct MyProfile{
 string firstname;
 string lastname;
 uint16 age;
 bool isMarried;
}
MyProfile[] public people;

现在让我们看看如何创建新的Person对象并将其添加到我们的people数组中。

创建一个新的人

Person James = Person(“James”,”Ryan”,35,true);

将该人添加到数组中

people.push(James);

我们也可以把这些结合起来,在一行代码中完成,以保持事情的简洁

people.push(Person(“James”,”Ryan”,35,true));

映射

映射允许程序员创建键值对来存储(作为一个列表)和查询数据。

它可以被看作是哈希表,它实际上被初始化了,使得每一个可能的键都存在,并被映射到一个值,其字节代表是所有的零:一个类型的默认值。

两个常用于映射键的数据类型[ key_type ]是地址和uint。
需要注意的是,并不是每一种数据类型都可以作为键值使用。例如,结构体和其他映射不能作为键使用。
与键不同,Solidity 并不限制值的数据类型 [ key_values ]。它可以是任何东西,包括结构体和其他映射。

映射被声明为

Mapping(_Keytype => _ValueType )

键类型几乎可以是任何类型,除了一个动态大小的数组、一个契约、一个枚举和一个结构。

contract MappingExample {
mapping(address => uint) public balances;
function update(uint newBalance) {
balances[msg.sender] = newBalance;  }}
contract MappingUser {
function f() returns (uint) {
MappingExample m = new MappingExample();
m.update(100);
return m.balances(this);
}}

控制结构

Solidity 遵循与 Java 脚本或 C 相同的控制结构语法。
所以有:if, else, while, do, for, break, continue, 与 C 或 JavaScript 的通常语义相同。

没有像C和JavaScript那样从非布尔类型到布尔类型的类型转换。

现在让我们看看这些控制结构是如何在 Solidity 中使用的。

contract ControlStructure {
address public variable1;
function ControlStructure>){

// if-else can be used like this
if(input1==2)
     variable1=1;
else
     variable1=0;


// while can be used like this
while(input1>=0){
if(input1==5)
     continue;
input1=input1-1;
     variable1++;
}


// for loop can be used like this
for(uint i=0;i<=50;i++) 
{ 
    variable1++; if(variable1==4) break; 
}

 
//do while can be used like this 
do { variable1--; } (while variable1>0);


// Conditional Operator can be used like this
bool IsTrue = (variable1 == 1)?true: false;
/*will show an error because
there is no type conversion from non-boolean to boolean
*/
if(1)
{
}

所以在这里我们总结一下Solidity中的控制结构和数据结构。