What is the difference between :: and . in Rust?

A useful distinction I found useful between :: and . is shown in Method Syntax.

When calling an instance of a fn in a struct, . is used:

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );
}

Associated functions on the other hand, are functions that do not take self as a param. They do not have an instance of the struct:

impl Rectangle {
    // Associated Function
    fn square(size: u32) -> Rectangle {
        Rectangle {
            width: size,
            height: size,
        }
    }
}

:: is used instead to call these functions.

fn main() {
    let sq = Rectangle::square(3);
}

Whereas . is used to return a method (a function of an instance of a struct).


. is used when you have a value on the left-hand-side. :: is used when you have a type or module.

Or: . is for value member access, :: is for namespace member access.

Tags:

Rust