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
- Regex example to match multiline string in Rust?
- How to map a Rust slice?
- How to replace a capture group using Rust regex?
- How to use regex captures in Rust?
- How to create a HashMap of structs in Rust?
- How to use non-capturing groups in Rust regex?
- How to match the end of a line in a Rust regex?
- How to use regex with bytes in Rust?
- How to perform matrix operations in Rust?
- How to use regex lookbehind in Rust?
See more codes...