rustRust lang class variable example
Class variables in Rust are declared using the static keyword. The following example shows how to declare a class variable in Rust:
struct Point {
x: i32,
y: i32,
}
impl Point {
// Declare a class variable
static origin: Point = Point { x: 0, y: 0 };
}
fn main() {
println!("The origin is: ({}, {})", Point::origin.x, Point::origin.y);
}
Output
The origin is: (0, 0)
Explanation:
struct Point: This declares a struct namedPointwith two fields,xandy.static origin: Point = Point { x: 0, y: 0 };: This declares a class variable namedoriginof typePointand initializes it with the valuePoint { x: 0, y: 0 }.println!("The origin is: ({}, {})", Point::origin.x, Point::origin.y);: This prints the value of theoriginclass variable.Point::origin.xandPoint::origin.y: This is how you access the fields of a class variable.
Helpful links:
More of Rust
- Generator example in Rust
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to use binary regex in Rust?
- How to use regex lookahead in Rust?
- How to make regex case insensitive in Rust?
- Regex example to match multiline string in Rust?
- How to use regex to match a double quote in Rust?
- Yield example in Rust
- How to use a tuple as a key in a Rust HashMap?
See more codes...