struct语法

struct类似于对于一个对象属性的封装。例如一个学生,可能会有姓名、学号等属性。将这些属性封装起来,成为一个结构体。

1
2
3
4
struct 对象名{
   变量类型1 变量名1;
   变量类型2 变量名2;
}

struct声明

定义一个学生类

1
2
3
4
struct student{
    uint grade;
    string name;
}

结构体不能包含自身

1
2
3
4
5
struct student{
    uint grade;
    string name;
    //student  s;结构体不能包含自身
}

结构体可以嵌套

一个结构体内部可以包含另一个结构体。

1
2
3
4
5
6
7
8
9
10
struct student{
    uint grade;
    string name;
}

struct student2{
 uint grade;
 string name;
  student ss; //包含另一个结构体
}

结构体内部可以包含自身的动态数组

1
2
3
4
5
struct student3{
 uint grade;
 string name;
  student3[] stu;//结构体内部可以包含自身的动态数组
}

结构体内部可以包含自身的mapping映射。

1
2
3
4
5
struct student4{
  uint grade;
  string name;
  mapping(uint=>student4) studentMap;
}

struct实例化

定义一个结构体有多种方式

1
2
3
4
5
6
7
8
9
struct student{
    uint grade;
    string name;
}
//方式一、将100、"jackson" 按顺序赋值给student。
student(100,"jackson")

//方式二、按名字赋值
student({name:"jackson",grade:100})

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
pragma solidity ^0.4.23;


contract structTest{

   struct student{
       uint grade;
       string name;
       //student  s;
   }


     struct student2{
       uint grade;
       string name;
        student ss;
   }

     struct student3{
       uint grade;
       string name;
        student ss;
        student3[] stu;

   }


    struct student4{
       uint grade;
       string name;
        student ss;
        student3[] stu;
        mapping(uint=>student4) studentMap;
   }

  function init() public pure returns(uint,string){
      student memory s = student(100,"jackson");
      student3[3] memory stu;
      return (s.grade,s.name);
  }


  function init2() public pure returns(uint,string){
      student memory s = student({name:"jackson",grade:100});
      return (s.grade,s.name);
  }
}

solidity智能合约[39]-结构体_区块链