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
- 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...