Methods
impl Blocks
Methods are defined inside impl Type { ... } blocks. Theimpl keyword groups related functions that operate on a particular struct type. The first parameter of each method is self, which gives access to the struct instance.
struct Point {
x: float;
y: float;
}
impl Point {
fn distance_from_origin(self) -> float {
return sqrt(self.x * self.x + self.y * self.y);
}
fn scale(self, factor: float) {
self.x = self.x * factor;
self.y = self.y * factor;
}
}Calling Methods
Methods are called with dot notation: instance.method(args). Theself parameter is automatically bound to the receiver.
fn main() {
let p = Point { x: 3.0, y: 4.0 };
let dist = p.distance_from_origin();
print("distance: " + dist);
p.scale(2.0);
print("scaled x: " + p.x);
print("scaled y: " + p.y);
}The self Parameter
The self parameter refers to the struct instance the method was called on. It acts like a regular variable inside the method body, allowing field reads and writes.
struct Counter {
value: int;
}
impl Counter {
fn new() -> Counter {
return Counter { value: 0 };
}
fn increment(self) {
self.value = self.value + 1;
}
fn get(self) -> int {
return self.value;
}
fn is_zero(self) -> bool {
return self.value == 0;
}
}Constructors
By convention, constructors are static methods that return a new instance. They do not take self and instead return the struct type directly.
struct Rectangle {
width: float;
height: float;
}
impl Rectangle {
fn new(w: float, h: float) -> Rectangle {
return Rectangle { width: w, height: h };
}
fn square(side: float) -> Rectangle {
return Rectangle { width: side, height: side };
}
}
fn main() {
let rect = Rectangle::new(10.0, 5.0);
let sq = Rectangle::square(4.0);
}Getter and Computation Methods
Methods can act as getters (returning a field) or perform computations using one or more fields.
struct Circle {
radius: float;
}
impl Circle {
fn diameter(self) -> float {
return self.radius * 2.0;
}
fn area(self) -> float {
return 3.14159 * self.radius * self.radius;
}
fn circumference(self) -> float {
return 2.0 * 3.14159 * self.radius;
}
}
fn main() {
let c = Circle { radius: 5.0 };
print(c.diameter());
print(c.area());
}Methods with Additional Parameters
Methods can accept parameters beyond self, just like regular functions.
struct Vec3 {
x: float;
y: float;
z: float;
}
impl Vec3 {
fn add(self, other: Vec3) -> Vec3 {
return Vec3 {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
};
}
fn dot(self, other: Vec3) -> float {
return self.x * other.x + self.y * other.y + self.z * other.z;
}
}