Structs let you create custom types by grouping related data together.
struct User {
username: String,
email: String,
active: bool,
sign_in_count: u64,
}let user = User {
username: String::from("alice"),
email: String::from("alice@example.com"),
active: true,
sign_in_count: 1,
};When variable names match field names:
fn create_user(username: String, email: String) -> User {
User {
username, // same as username: username
email, // same as email: email
active: true,
sign_in_count: 1,
}
}In Solana, program accounts are modeled as structs with careful memory layouts!
User struct with name: String and age: u32create_user to create a User instancegreet to return a greeting stringname and agegreet returns: "Hi, I'm {name} and I'm {age} years old"User("Alice", 30)String::from(name) or name.to_string() to convert &str to Stringformat!() macro to build the greeting string:
format!("Hi, I'm {} and I'm {} years old", user.name, user.age)