# Solidity极简入门: 6. 数组和结构体, array, struct

By [0xAA](https://paragraph.com/@wtfacademy) · 2022-04-09

---

我最近在重新学solidity，巩固一下细节，也写一个“Solidity极简入门”，供小白们使用（编程大佬可以另找教程），每周更新1-3讲。

欢迎关注我的推特：[@0xAA\_Science](https://twitter.com/0xAA_Science)

WTF技术社群discord，内有加微信群方法：[链接](https://discord.gg/5akcruXrsk)

所有代码和教程开源在github（1024个star发课程认证，2048个star发社群NFT）: [github.com/AmazingAng/WTFSolidity](https://github.com/AmazingAng/WTFSolidity)

* * *

这一讲，我们将介绍solidity中的两个重要变量类型：数组（array）和结构体（struct）

数组 array
--------

数组（Array）是solidity常用的一种变量类型，用来存储一组数据（整数，字节，地址等等）。数组分为固定长度数组和可变长度数组两种：

*   **固定长度数组**：在声明时指定数组的长度。用T\[k\]的格式声明，其中T是元素的类型，k是长度，例如：
    

        // 固定长度 Array
        uint[8] array1;
        byte[5] array2;
        address[100] array3;
    

*   **可变长度数组**：在声明时不指定数组的长度。用T\[\]的格式声明，其中T是元素的类型，例如（bytes比较特殊，是数组，但是不用加\[\]）：
    

        // 可变长度 Array
        uint[] array4;
        byte[] array5;
        address[] array6;
        bytes array7;
    

### 创建数组的规则

在solidity里，创建数组有一些规则：

*   对于memory可变长度数组，可以用new操作符来创建，但是必须声明长度，并且长度不能改变。例子：
    

        // memory可变长度 Array
        uint[] memory array8 = new uintUnsupported embed;
        bytes memory array9 = new bytes(9);
    

*   数组字面常数是写作表达式形式的数组，并且不会立即赋值给变量，例如 `[uint(1),2,3]`（需要声明第一个元素的类型，不然默认用存储空间最小的类型）
    
*   如果创建的是dynamic array，你需要一个一个元素的赋值。
    

            uint[] memory x = new uintUnsupported embed;
            x[0] = 1;
            x[1] = 3;
            x[2] = 4;
    

### 数组成员

*   **length**: 数组有一个包含元素数量的length成员， 内存数组的长度在创建后是固定的。
    
*   **push()**:可变长度数组 和 `bytes`拥有 `push()` 成员，可以在数组最后添加一个0元素。
    
*   **push(x):** 可变长度数组 和 bytes拥有 `push(x)` 成员，可以在数组最后添加一个x元素。
    
*   **pop**: 可变长度数组 和 bytes拥有 `pop` 成员，可以移除数组最后一个元素。
    

结构体 struct
----------

Solidity 支持通过构造结构体的形式定义新的类型。创建结构体的方法：

        // 结构体
        struct Student{
            uint256 id;
            uint256 score; 
        }
    
        Student student; // 初始一个student结构体
    

给结构体赋值的两种方法：

        //  给结构体赋值
        // 方法1:在函数中创建一个storage的struct引用
        function initStudent1() external{
            Student storage _student = student; // assign a copy of student
            _student.id = 11;
            _student.score = 100;
        }
    
         // 方法2:直接引用状态变量的struct
        function initStudent2() external{
            student.id = 1;
            student.score = 80;
        }
      
    

总结
--

这一讲，我们介绍了solidity中数组（array）和结构体（struct）的基本用法。下一讲我们将介绍solidity中的哈希表——映射（mapping）。

---

*Originally published on [0xAA](https://paragraph.com/@wtfacademy/solidity-6-array-struct)*
