Title here
Summary here
Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.
This person struct type has name and age fields.
struct Person {
name: String,
age: i32,
}new_person constructs a new person struct with the given name.
Rust ensures memory safety through its ownership system, so you can safely return a struct from a function.
fn new_person(name: String) -> Person {
let p = Person { name, age: 42 };
p
}You can create a new struct instance using this syntax.
fn main() {
println!("{:?}", Person { name: String::from("Bob"), age: 20 });
println!("{:?}", Person { name: String::from("Alice"), age: 30 });
println!("{:?}", Person { name: String::from("Fred"), age: 0 });
println!("{:?}", &Person { name: String::from("Ann"), age: 40 });
println!("{:?}", new_person(String::from("Jon")));
let s = Person { name: String::from("Sean"), age: 50 };
println!("{}", s.name);
let sp = &s;
println!("{}", sp.age);
let mut sp = s;
sp.age = 51;
println!("{}", sp.age);
let dog = struct {
name: String,
is_good: bool,
} {
name: String::from("Rex"),
is_good: true,
};
println!("{:?}", dog);
}To run the program, put the code in main.rs and use cargo run.
$ cargo run
Person { name: "Bob", age: 20 }
Person { name: "Alice", age: 30 }
Person { name: "Fred", age: 0 }
Person { name: "Ann", age: 40 }
Person { name: "Jon", age: 42 }
Sean
50
51
{ name: "Rex", is_good: true }Now that we can run and build basic Rust programs, let’s learn more about the language.
Comments powered by Disqus