rustHow to extend class in Rust lang
In Rust, you can extend a class by using the impl keyword. This allows you to add methods and fields to an existing class. Here is an example of extending a class in Rust:
struct Person {
name: String,
age: u8
}
impl Person {
fn new(name: String, age: u8) -> Person {
Person {
name,
age
}
}
fn get_name(&self) -> &String {
&self.name
}
}
fn main() {
let person = Person::new("John".to_string(), 30);
println!("Name: {}", person.get_name());
}
Output
Name: John
Explanation:
struct Person: This defines a struct calledPersonwith two fields,nameandage.impl Person: This is theimplblock which allows us to extend thePersonstruct.fn new: This is a constructor method which takes two parameters,nameandage, and returns aPersoninstance.fn get_name: This is a method which takes a&selfparameter and returns a reference to thenamefield of thePersoninstance.let person: This creates a newPersoninstance using thenewconstructor method.println!: This prints out thenamefield of thePersoninstance.
Helpful links:
More of Rust
- How to match the end of a line in a Rust regex?
- How to use binary regex in Rust?
- Regex example to match multiline string in Rust?
- How to use regex to match a double quote in Rust?
- How to print a Rust HashMap?
- How to match digits with regex in Rust?
- How to use regex captures in Rust?
- How to create a HashMap of structs in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to lock a Rust HashMap?
See more codes...