简体   繁体   English

:: 和. 之间有什么区别? 在 Rust?

[英]What is the difference between :: and . in 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 “编程猜谜游戏”来自The Rust Programming Language

In the above case, I access the function new() in String .在上述情况下,我在String中访问 function new() What is the difference between String::new() and String.new() ? String::new()String.new()有什么区别? Is .. only for methods?只针对方法?

. 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.用于值成员访问, ::用于命名空间成员访问。

A useful distinction I found useful between :: and .我发现::. is shown in Method Syntax .显示在方法语法中

When calling an instance of a fn in a struct , .struct调用fn的实例时, . 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.另一方面,关联函数是不将self作为参数的函数。 They do not have an instance of the struct :他们没有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).用于返回一个方法(结构实例的函数)。

I like to think if the method takes &self as a parameter, we use .我想如果该方法将&self作为参数,我们使用. syntax and if it does not, then we use :: syntax.语法,如果没有,那么我们使用::语法。

For example, to quote @Dan's answer, to calculate the area, we need an object, it's length and it's height and so we pass &self as a parameter and we use .例如,引用@Dan 的回答,要计算面积,我们需要一个 object,它是lengthheight ,所以我们将&self作为参数传递,我们使用. syntax.句法。 To create a new square, we don't need an existing object and we use :: syntax.要创建一个新方块,我们不需要现有的 object,我们使用::语法。

x.do() just means execute the function do() on the object x and x::do() means execute the function do() from the namespace of x . x.do()只是表示在 object x上执行 function do() ,而x::do()表示从x的命名空间执行 function do()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM