Solidity 入门教程(二):值类型全解 —— 布尔、整数、地址与字节数组

发布于:2025-06-24 ⋅ 阅读:(13) ⋅ 点赞:(0)

在上一章中,我们写下了第一个 Solidity 合约并在 Remix 中成功运行。本章我们将深入了解 Solidity 中的几种常用值类型(Value Types),并通过示例代码在 Remix 进行验证。

一、Solidity 中的三种数据类型

在 Solidity 中,数据类型可以分为三大类:

本章重点讲解值类型,引用和映射类型将在后续章节深入讲解。

二、常见的值类型介绍与用法

我们从最常用的四种开始:布尔型、整型、地址类型和字节数组。

  • 布尔类型(bool)
bool public isActive = true;

布尔型只有两个值:truefalse。常用于条件判断、逻辑开关等场景。

  • 整型(int / uint)

Solidity 中支持有符号整型 int无符号整型 uint,可指定位数(如 uint8uint256)。

int public signedInt = -42;
uint public unsignedInt = 100;
  • int: 可以为负,如 -1

  • uint: 只能为正,默认 uint256

不同位数的整型占用不同的存储空间。

  • 地址类型(address)

在 Solidity 中,地址类型用于表示以太坊账户地址(无论是用户账户还是合约账户)。

Solidity 中地址类型分为两类:

address public normalAddress = msg.sender;
address payable public payableAddress = payable(msg.sender);

用法区别:

// address 类型不能直接接收以太币
// normalAddress.transfer(1 ether); ❌ 编译错误

// address payable 可以接收以太币
payableAddress.transfer(1 ether); ✅ 正确
  • 字节数组(bytes / bytesN)

定长字节数组(bytes1 ~ bytes32);不定长字节数组(bytes)

bytes1 public a = 0x01;
bytes32 public b = "Hello Bytes32!";
bytes public c = "Dynamic Bytes";

字节数组用于存储二进制数据,常见于加密、哈希等场景。

三、完整示例代码

将下面的代码粘贴到 Remix 中运行,即可观察每种类型的结果:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;

contract ValueTypesDemo {
    // 布尔值
    bool public isActive = true;

    // 整型
    int public signedInt = -42;
    uint public unsignedInt = 2025;

    // 地址类型
    address public normalAddress = msg.sender;
    address payable public payableAddress = payable(msg.sender);

    // 字节数组
    bytes1 public oneByte = 0x01;
    bytes32 public fixedBytes = "Fixed length byte array";
    bytes public dynamicBytes = "Hello, dynamic bytes!";
}

在 Remix 上运行效果:

四、小结


网站公告

今日签到

点亮在社区的每一天
去签到