Similar to Rust, Sway comes with its own standard library.
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, like
Result<T, E> and
Option<T>, 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.
The entire Sway standard library is a Forc project called
std, and is available directly here: https://github.com/FuelLabs/sway/tree/master/sway-lib-std (navigate to the appropriate tagged release if the latest
master is not compatible).
The standard library is made implicitly available to all Forc projects created using
forc new. In other words, it is not required to manually specify
std as an explicit dependency. Forc will automagically use the version of
std that matches its version.
Importing items from the standard library can be done using the
use keyword, just as importing items from any Sway project. For example:
This imports the
StorageMap type into the current namespace.
Sway comes with a variety of things in its standard library. However, if you had to manually import every single thing that you used, it would be very verbose. But importing a lot of things that a program never uses isn't good either. A balance needs to be struck.
The prelude is the list of things that Sway automatically imports into every Sway program. It's kept as small as possible, and is focused on things which are used in almost every single Sway program.
The current version of the prelude lives in
std::prelude, and re-exports the following:
std::address::Address, a wrapper around the
b256type representing a wallet address.
std::contract_id::ContractId, a wrapper around the
b256type representing the ID of a contract.
std::identity::Identity, an enum with two possible variants:
std::vec::Vec, a growable, heap-allocated vector.
std::assert::assert, a function that reverts the VM if the condition provided to it is
std::revert::require, a function that reverts the VM and logs a given value if the condition provided to it is
std::revert::revert, a function that reverts the VM.