Sway is fundamentally a blockchain language, and it offers a selection of types tailored for the blockchain use case.
Sway从根本上说是一种区块链语言,它为区块链的使用情况提供了一系列的类。
These are provided via the standard library (lib-std) which both add a degree of type-safety, as well as make the intention of the developer more clear.
The Address type is a type-safe wrapper around the primitive b256 type. Unlike the EVM, an address never refers to a deployed smart contract (see the ContractId type below). An Address can be either the hash of a public key (effectively an externally owned account if you're coming from the EVM) or the hash of a predicate. Addresses own UTXOs.
Casting between the b256 and Address types must be done explicitly:
b256 和Address类型之间的转换必须明确进行:
let my_number: b256 = 0x000000000000000000000000000000000000000000000000000000000000002A;
let my_address: Address = Address::from(my_number);
let forty_two: b256 = my_address.into();
ContractId类 (ContractId Type)
The ContractId type is a type-safe wrapper around the primitive b256 type. A contract's ID is a unique, deterministic identifier analogous to a contract's address in the EVM. Contracts cannot own UTXOs but can own assets.
Casting between the b256 and ContractId types must be done explicitly:
b256 和 ContractId类型之间的转换必须明确进行:
Identity 类 (Identity Type)
The Identity type is an enum that allows for the handling of both Address and ContractId types. This is useful in cases where either type is accepted, e.g. receiving funds from an identified sender, but not caring if the sender is an address or a contract.
A match statement can be used to return to an Address or ContractId as well as handle cases in which their execution differs.
match 语句可用于返回到Address 或 ContractId ,以及处理它们执行不同的情况。
A common use case for Identity is for access control. The use of Identity uniquely allows both ContractId and Address to have access control inclusively.
let my_number: b256 = 0x000000000000000000000000000000000000000000000000000000000000002A;
let my_contract_id: ContractId = ContractId::from(my_number);
let forty_two: b256 = my_contract_id.into();
let raw_address: b256 = 0xddec0e7e6a9a4a4e3e57d08d080d71a299c628a46bc609aab4627695679421ca;
let my_identity: Identity = Identity::Address(Address::from(raw_address));
let my_contract_id: ContractId = match my_identity {
Identity::ContractId(identity) => identity,
_ => revert(0),
};