值类型与引用类型

Solidity 中的变量类型可以分为两大类:

  • 值类型
  • 引用类型

他们的主要区别主要在于,值类型在使用时(例如函数传参),总是直接拷贝一个副本使用,而引用类型是传递一个引用:

ValueRefType.sol
运行
复制
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

contract ValueRefType {
    struct People {
        uint age;
    }

    function add1Year(uint age, People memory p) private pure {
        age += 1;   // 修改 age
        p.age += 1; // 修改 p.age
    }

    function test() public pure returns (uint, uint) {
      uint age = 0;
      People memory p;
      p.age = 0;
      // uint 为值类型,add1Year 得到的是 age 的一份拷贝
      // struct People 为引用类型,add1Year 得到的是 p 的引用
      add1Year(age, p);
      return (age, p.age); // = (0, 1),add1Year 通过 p 的引用,修改了 p.age
    }
}

Solidity 中只有四种引用类型:

  • 动态数组 array
  • 字符串 string(可以视为动态字节数组)
  • 结构体 struct
  • 字典 mapping

Solidity 包含以下值类型:

  • 布尔型
  • 整数型
  • 定点小数
  • 地址
  • 合约类型
  • 固定长度的数组
  • 字面量
    • 数字字面量
    • 字符串字面量
      • Unicode 字符串字面量
    • 地址字面量
    • 十六进制字面量
  • 函数
  • 自定义类型

值类型变量的长度在编译时就可以确定。