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 thePerson
class and sets thename
property toJohn
.println!("Name: {}", person.name);
: This line prints the value of thename
property.
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...