Library
A library is used to contain code that performs common operations in order to prevent code duplication.
Definition
Libraries are defined using the library
keyword at the beginning of a file.
library;
Accessibility
Code defined inside a library, but more generally anywhere inside a Sway project, is considered to be private
which means that it is inaccessible to other files unless explicitly exposed.
Code can be exposed through a two step process:
- Add a
pub
keyword at the start of some code - Specify the library in the
Forc.toml
file as a dependency and then import thepub
declaration
library;
// Cannot import because the `pub` keyword is missing
fn foo() {}
// Can import everything below because they are using the `pub` keyword
pub const ONE = __to_str_array("1");
pub struct MyStruct {}
impl MyStruct {
pub fn my_function() {}
}
pub enum MyEnum {
Variant: (),
}
pub fn bar() {}
pub trait MyTrait {
fn my_function();
}
The following structures can be marked as pub
:
- Globally defined constants
- Structs
- Enums
- Functions
- Traits
Deployment
Libraries cannot be directly deployed to a blockchain, but they can be deployed as part of a contract.