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 namedPoint
with two fields,x
andy
.static origin: Point = Point { x: 0, y: 0 };
: This declares a class variable namedorigin
of typePoint
and initializes it with the valuePoint { x: 0, y: 0 }
.println!("The origin is: ({}, {})", Point::origin.x, Point::origin.y);
: This prints the value of theorigin
class variable.Point::origin.x
andPoint::origin.y
: This is how you access the fields of a class variable.
Helpful links:
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to split a string with Rust regex?
- How to iterate over a Rust slice with an index?
- How to use negation in Rust regex?
- How to use regex captures in Rust?
- Regex example to match multiline string in Rust?
- How to get a capture group using Rust regex?
- How to use modifiers in a Rust regex?
- How to create a HashMap of structs in Rust?
See more codes...