rustRust lang class with constructor example
A constructor in Rust is a function that is called when an instance of a struct is created. It is used to initialize the fields of the struct with the given values.
Below is an example of a Rust class with a constructor:
struct Person {
name: String,
age: u8
}
impl Person {
fn new(name: String, age: u8) -> Person {
Person {
name,
age
}
}
}
fn main() {
let person = Person::new(String::from("John"), 30);
println!("{} is {} years old", person.name, person.age);
}
Output
John is 30 years old
Explanation:
- The
struct Persondefines a struct with two fields,nameandage, both of typeStringandu8respectively. - The
impl Personblock defines an implementation block for thePersonstruct. - The
fn newfunction is the constructor for thePersonstruct. It takes two parameters,nameandage, both of typeStringandu8respectively. - The
let personstatement creates an instance of thePersonstruct using thePerson::newconstructor. - The
println!statement prints out the name and age of thepersoninstance.
Helpful links:
More of Rust
- Regex example to match multiline string in Rust?
- How to map a Rust slice?
- How to replace a capture group using Rust regex?
- How to use regex captures in Rust?
- How to create a HashMap of structs in Rust?
- How to use non-capturing groups in Rust regex?
- How to match the end of a line in a Rust regex?
- How to use regex with bytes in Rust?
- How to perform matrix operations in Rust?
- How to use regex lookbehind in Rust?
See more codes...