Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

I am confused by the difference between :: and .. They look the same except that their syntax are different.

let mut guess = String::new();

io::stdin().read_line(&mut guess)
    .expect("Failed to read line");

"Programming a Guessing Game" from The Rust Programming Language

In the above case, I access the function new() in String. What is the difference between String::new() and String.new()? Is . only for methods?

like image 474
Dan Avatar asked Aug 08 '18 00:08

Dan


People also ask

What does :: mean in Rust?

Please review Appendix B: Operators and Symbols of The Rust Programming Language. In this case, the double colon ( :: ) is the path separator. Paths are comprised of crates, modules, and items. The full path for your example item, updated for 1.0 is: std::usize::BITS.

What is ampersand in Rust?

An ampersand ( & ) is used with a variable's name while passing its reference instead of its value to a function. The function's signature should also have an ampersand with the type of argument that receives the reference. When a function takes in a reference as a parameter, it is called borrowing.


2 Answers

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

like image 132
Dan Avatar answered Sep 29 '22 03:09

Dan


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

like image 32
DK. Avatar answered Sep 29 '22 01:09

DK.