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
- Generator example in Rust
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to use binary regex in Rust?
- How to use regex lookahead in Rust?
- How to make regex case insensitive in Rust?
- Regex example to match multiline string in Rust?
- How to use regex to match a double quote in Rust?
- Yield example in Rust
- How to use a tuple as a key in a Rust HashMap?
See more codes...