rustRust lang class property
Class properties in Rust are defined using the pub keyword. This keyword makes the property accessible from outside the class. The syntax for defining a class property is as follows:
pub property_name: type
For example, if we want to define a class property called name of type String, we can do so as follows:
pub name: String
The following is an example of a class with a property called name of type String:
pub struct Person {
pub name: String,
}
fn main() {
let person = Person {
name: String::from("John"),
};
println!("Name: {}", person.name);
}
Output
Name: John
Explanation:
pub: This keyword makes the property accessible from outside the class.name: This is the name of the property.String: This is the type of the property.Person: This is the name of the class.let person = Person { name: String::from("John") };: This line creates an instance of thePersonclass and sets thenameproperty toJohn.println!("Name: {}", person.name);: This line prints the value of thenameproperty.
Helpful links:
More of Rust
- Regex example to match multiline string in Rust?
- How to map a Rust slice?
- How to replace a capture group using Rust regex?
- How to use regex captures in Rust?
- How to create a HashMap of structs in Rust?
- How to use non-capturing groups in Rust regex?
- How to match the end of a line in a Rust regex?
- How to use regex with bytes in Rust?
- How to perform matrix operations in Rust?
- How to use regex lookbehind in Rust?
See more codes...