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
- How to get a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to replace strings using Rust regex?
- How to use non-capturing groups in Rust regex?
- Word boundary example in regex in Rust
- How to use regex to match a group in Rust?
- Example of struct private field in Rust
- How to multiply matrices in Rust?
- How to parse JSON string in Rust?
- How to initialize a Rust HashMap?
See more codes...