Rust structs
Created By: chatGPT
In Rust, a struct is a custom data type that lets you package together related data. Structs are similar to classes in other programming languages and allow for the creation of complex data types. You can define fields in a struct and then create instances of that struct with those fields. Here’s how you can define a struct and use it:
struct Person {
name: String,
age: u32,
}
fn main() {
let person = Person {
name: String::from("Alice"),
age: 30,
};
println!("Name: {}, Age: {}", person.name, person.age);
}
You can also define methods for your structs. This is done using the impl block. Here’s an example of how to implement a method for the Person struct that greets the person:
impl Person {
fn greet(&self) -> String {
format!("Hello, my name is {}.", self.name)
}
}
fn main() {
let person = Person {
name: String::from("Bob"),
age: 25,
};
println!("{}", person.greet());
}
If you want to allow for inheritance-like behavior, you can use traits. This allows you to define shared behavior for multiple structs. Here’s an example that adds a
descripiton
method using a trait:trait Describable {
fn description(&self) -> String;
}
impl Describable for Person {
fn description(&self) -> String {
format!("{} is {} years old.", self.name, self.age)
}
}
fn main() {
let person = Person {
name: String::from("Charlie"),
age: 22,
};
println!("{}", person.description());
}
You can also create tuple structs, which are structs that do not have named fields. Here’s an example of a tuple struct called
Point
:struct Point(i32, i32);
fn main() {
let origin = Point(0, 0);
println!("Point coordinates: ({}, {})", origin.0, origin.1);
}