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 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...