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 use regex captures in Rust?
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to parse a file with Rust regex?
- How to get size of pointer in Rust
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use regex lookahead in Rust?
See more codes...