Sway编程语言-更新中(The Sway Programming Language-Updatin
  • Sway编程语言(The Sway Programming Language)
  • 1. 导言(Introduction)
    • 1.1 安装(Installation)
    • 1.2 Sway快速入门 (Sway Quickstart)
    • 1.3 Fuel工具链 (The Fuel Toolchain)
    • 1.4 一个Forc项目 (A Forc Project)
    • 1.5 标准库 (Standard Library)
  • 2. 示例(Example)
    • 2.1计数器(Counter)
    • 2.2子货币(Subcurrency)
    • 2.3 FizzBuzz
    • 2.4 钱包智能合约(Wallet Smart Contract)
  • 3.Sway编程类型(Sway Program Types)
    • 3.1 合约(Contracts)
    • 3.2 库 (Libraries)
    • 3.3 脚本(Scripts)
    • 3.4 谓词 (Predicates)
  • 4. Sway语言基础 (Sway Language basics)
    • 4.1 变量 (Variables)
    • 4.2 内置类型(Built-in Types)
    • 4.3 常用库类型(Commonly Used Library Types)
    • 4.4 区块链类 (Blockchain Types)
    • 4.5 函数 (Functions)
    • 4.6 结构、元祖和穷举 (Structs, Tuples, and Enums)
    • 4.7 方法和关联函数 (Methods and Associated Functions)
    • 4.8 注释和日志 (Comments and Logging)
    • 4.9 控制流 (Control Flow)
  • 5. 用Sway部署区块链 (Blockchain Development with Sway)
    • 5.1 哈希和加密学 (Hashing and Cryptography)
    • 5.2 合约存储(Contract Storage)
    • 5.3 函数纯度 (Function Purity)
    • 5.4 标识符(Identifiers)
    • 5.5 原生资产(Native Assets)
    • 5.6 访问控制 (Access Control)
    • 5.7 调用合约(Calling Contracts)
  • 6. 高级概念 (Advanced Concepts)
    • 6.1 高级类型 (Advanced Types)
    • 6.2 通用类型 (Generic Types)
    • 6.3 特征 (Traits)
    • 6.4 集 (Assembly)
  • 7. 一般集聚 (Common Collections)
    • 7.1 堆上的向量(Vectors on the Heap)
    • 7.2 存储向量 (Storage Vectors)
    • 7.3 存储映射 (Storage Maps)
  • 8.测试(Testing)
    • 8.1 单元测试(Unit Testing)
    • 8.2 用Rust来测试 (Testing with Rust)
  • 9.应用前端开发 (Application Frontend Development)
    • 9.1 TypeScript SDK
  • 10.Sway应用(Sway Reference)
    • 10.1 编译器内部函数(Compiler Intrinsics)
    • 10.2 属性(Attributes)
    • 10.3 风格向导(Style Guide)
    • 10.4 已知各类问题(Known Issues and Workarounds)
    • 10.5 与Solidity的不同之处 (Differences From Solidity)
    • 10.6 与Rust的不同之处 (Differences From Rust)
    • 10.7 向Sway贡献 (Contributing To Sway)
  • 11. Forc引用 (Forc Reference)
    • 11.1清单参考 (Manifest Reference)
    • 11.2 工作区(Workspaces)
    • 11.3 依赖(Dependencies)
    • 11.4 命令(Commands)
      • 11.4.1 forc-addr2line
      • 11.4.2 forc-build
      • 11.4.3 forc-check
Powered by GitBook
On this page
  • Result<T, E>
  • Option<T>
  1. 4. Sway语言基础 (Sway Language basics)

4.3 常用库类型(Commonly Used Library Types)

Previous4.2 内置类型(Built-in Types)Next4.4 区块链类 (Blockchain Types)

Last updated 1 year ago

The Sway Standard Library is the foundation of portable Sway software, a set of minimal shared abstractions for the broader Sway ecosystem. It offers core types, library-defined operations on language primitives, native asset management, blockchain contextual operations, access control, storage management, and support for types from other VMs, among many other things. Reference the standard library docs .

Sway标准库是可移植的Sway软件的基础,是更广泛的Sway生态系统的一组最小共享抽象。它提供了核心类型、库定义的语言基元操作、原生资产管理、区块链背景操作、访问控制、存储管理以及对其他虚拟机的类型支持,还有其他许多东西。参考标准库文档。

Result<T, E>

Type Result is the type used for returning and propagating errors. It is an enum with two variants: Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value. The T and E in this definition are type parameters, allowing Result to be generic and to be used with any types.

Result类型是用于返回和传播错误的类型。它是一个enum,有两个变体:Ok(T),代表成功并包含一个值,Err(E),代表错误并包含一个错误值。这个定义中的T 和 E是类型参数,使得Result成为通用,即用于任何类型。

/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
pub enum Result<T, E> {
    /// Contains the success value.
    Ok: T,
    /// Contains the error value.
    Err: E,
}

Functions return Result whenever errors are expected and recoverable. Take the following example:

只要是预期的、可恢复的错误,函数都会返回Result。以下面的例子为例:

script;

enum MyContractError {
    DivisionByZero: (),
}

fn divide(numerator: u64, denominator: u64) -> Result<u64, MyContractError> {
    if (denominator == 0) {
        return Result::Err(MyContractError::DivisionByZero);
    } else {
        Result::Ok(numerator / denominator)
    }
}

fn main() -> Result<u64, str[4]> {
    let result = divide(20, 2);
    match result {
        Result::Ok(value) => Result::Ok(value),
        Result::Err(MyContractError::DivisionByZero) => Result::Err("Fail"),
    }
}

Option<T>

Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. Option types are very common in Sway code, as they have a number of uses:

Option类型代表一个可选值:每个Option要么是Some,包含一个值,要么是None,不包含。Option类型在Sway代码中非常常见,因为它们有很多用途:

  • Initial values where None can be used as an initializer. 初始值,其中None可以作为初始化器使用。

  • Return value for otherwise reporting simple errors, where None is returned on error. 返回值,用于报告简单的错误,其中None在错误时被返回。

/// A type that represents an optional value, either `Some(val)` or `None`.
pub enum Option<T> {
    /// No value.
    None: (),
    /// Some value of type `T`.
    Some: T,
}

Option is commonly paired with pattern matching to query the presence of a value and take action, allowing developers to choose how to handle the None case.

Option通常与模式匹配配对,以查询一个值的存在并采取行动,让开发者选择如何处理 None情况。

Below is an example that uses pattern matching to handle invalid divisions by 0 by returning an Option:

下面是一个使用模式匹配的例子,通过返回一个 Option 来处理无效的,除以0的除法:

script;

fn divide(numerator: u64, denominator: u64) -> Option<u64> {
    if denominator == 0 {
        Option::None
    } else {
        Option::Some(numerator / denominator)
    }
}

fn main() {
    let result = divide(6, 2);
    // Pattern match to retrieve the value
    match result {
        // The division was valid
        Option::Some(x) => std::logging::log(x),
        // The division was invalid
        Option::None => std::logging::log("Cannot divide by 0"),
    }
}

The implementation of Option matches on the variant: if it's Ok it returns the inner value, if it's None, it . Option的实现在变体上是匹配的:如果是Ok则返回内部值,如果是None则。

here
在这里
reverts
返还 reverts