Constructor
Constructors are a special type of function that runs only once when deploying a contract, and can be used to initialize the state of the contract. Your contract must not have more than one constructor, and that constructor function must be annotated with the #[constructor]
attribute. Also, a good practice consists in naming that function constructor
.
Here's a simple example that demonstrates how to initialize the state of a contract on deployment by defining logic inside a constructor.
#[starknet::contract]
pub mod ExampleConstructor {
use starknet::ContractAddress;
use starknet::storage::{Map, StorageMapWriteAccess};
#[storage]
struct Storage {
pub names: Map::<ContractAddress, felt252>,
}
// The constructor is decorated with a `#[constructor]` attribute.
// It is not inside an `impl` block.
#[constructor]
fn constructor(ref self: ContractState, name: felt252, address: ContractAddress) {
self.names.write(address, name);
}
}