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 Person
defines a struct with two fields,name
andage
, both of typeString
andu8
respectively. - The
impl Person
block defines an implementation block for thePerson
struct. - The
fn new
function is the constructor for thePerson
struct. It takes two parameters,name
andage
, both of typeString
andu8
respectively. - The
let person
statement creates an instance of thePerson
struct using thePerson::new
constructor. - The
println!
statement prints out the name and age of theperson
instance.
Helpful links:
More of Rust
- How to match a URL with a regex in Rust?
- How to replace all matches using Rust regex?
- How to ignore case in Rust regex?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to get a capture group using Rust regex?
- How to use regex captures in Rust?
- How to use named capture groups in Rust regex?
- How to use regex with bytes in Rust?
- How to use regex to match a group in Rust?
See more codes...