Rust Programming: Automatic Referencing

0

Rust does not have an equivalent to the -> operator. Instead, Rust uses automatic referencing and dereferencing when calling methods. This means that you can simply use the . operator to call a method on an object, regardless of whether the object is a reference or a pointer. Rust will automatically add in the appropriate &, &mut, or * to make the call work.

This automatic referencing behavior is one of the things that makes Rust's ownership system so ergonomic. It means that you don't have to worry about manually dereferencing pointers when calling methods, which can help to reduce errors. The following code shows an example of how automatic referencing works in Rust:

struct Point {

    x: i32,

    y: i32,

}


impl Point {

    fn distance(&self, other: &Point) -> i32 {

        // This call to distance uses automatic referencing to ensure that self is

        // a reference, even though it is passed as an immutable value.

        self.x.abs() + other.y.abs()

    }

}


fn main() {

    let p1 = Point { x: 1, y: 2 };

    let p2 = Point { x: 3, y: 4 };


    // This call to distance uses automatic referencing to ensure that p1 is

    // dereferenced before calling the method.

    println!("{}", p1.distance(&p2));

}

This code will print the number 7, which is the distance between the two points. The `distance` method takes a reference to another `Point` as its argument, so Rust automatically adds in the & to ensure that `p1` is a reference. This prevents us from accidentally mutating `p1` when we call the method.

Automatic referencing is a powerful feature that can help to make Rust code more concise and easier to read.

Post a Comment

0Comments
Post a Comment (0)