4.3 常用库类型(Commonly Used Library Types)
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 here.
Sway标准库是可移植的Sway软件的基础,是更广泛的Sway生态系统的一组最小共享抽象。它提供了核心类型、库定义的语言基元操作、原生资产管理、区块链背景操作、访问控制、存储管理以及对其他虚拟机的类型支持,还有其他许多东西。在这里参考标准库文档。
Result<T, E>
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
成为通用,即用于任何类型。
Functions return Result
whenever errors are expected and recoverable. Take the following example:
只要是预期的、可恢复的错误,函数都会返回Result
。以下面的例子为例:
Option<T>
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
在错误时被返回。
The implementation of Option
matches on the variant: if it's Ok
it returns the inner value, if it's None
, it reverts. Option
的实现在变体上是匹配的:如果是Ok
则返回内部值,如果是None
则返还 reverts。
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的除法:
Last updated