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 calledPerson
with two fields,name
andage
.impl Person
: This is theimpl
block which allows us to extend thePerson
struct.fn new
: This is a constructor method which takes two parameters,name
andage
, and returns aPerson
instance.fn get_name
: This is a method which takes a&self
parameter and returns a reference to thename
field of thePerson
instance.let person
: This creates a newPerson
instance using thenew
constructor method.println!
: This prints out thename
field 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...