从 Rust 中相同 class 的另一个静态方法引用静态方法的最佳方法是什么?

What is the best way to refer to a static method from another static method of the same class in Rust?

在一个新的 Rust 模块中,我可以写:

struct myStruct {
    x : u32
}

impl myStruct {
    fn new() -> myStruct{
        myStruct{ x : other()}
    }

    fn other() -> u32 {
        6
    }
}

来自其他 OO 语言,我希望 other()new() 的范围内。也就是说,我希望能够从 class 的另一个静态方法调用 class 的一个静态方法。但是,rustc 会生成消息:

error[E0425]: cannot find function `other` in this scope
 --> dummy_module.rs:9:23
  |
9 |         myStruct{ x : other()}
  |                       ^^^^^ not found in this scope

相比之下,以下 Java 代码编译良好:

public class myStruct{
    int x;

    public myStruct(){
        x = other();
    }

    private int other(){
        return 5;
    }
}

我不记得在我使用的 Rust 书中看到过任何提及,而且我似乎无法在网上找到明确的答案。我可以通过使用 myStruct::other() 显式确定对 other 的调用范围来修复它,但这看起来很麻烦。如果我尝试 use myStruct,则会收到神秘消息

7 |     use myStruct;
  |     ^^^ unexpected token

是否总是需要这种明确的范围界定?如果是,为什么?

我做错了什么吗?是否有惯用的解决方法?

是的,它是有意的,因为生锈不是 Java ;)

你可以这样写:

myStruct { x: myStruct::other() }

myStruct { x: Self::other() }

我无法告诉您确切的设计决定,为什么 Self 函数不会自动导入,但您可以 "work-around" 使用正确的路径。

Rust 设计者做出了以下选择:与作用域相关的所有内容都是显式的。因此,正如您必须键入 self 才能从另一个成员函数调用成员函数:self.foo(),您必须使用 Self 调用静态成员:Self::bar().

我认为是这种情况,因为 self 不能隐含:实际上它必须作为参数添加或借用,这与 Java 不同,其中 this 总是取值。因此,因为 self 已经是一个显式参数,所以需要它作为显式调用者以保持一致性。

由于其内存模型,Rust 的明确性允许提供更好的错误消息。例如,考虑以下代码:

struct Struct;

impl Struct {
    fn foo(&mut self) {
        self.consume();
    }

    fn consume(self) {}
}

错误信息是:

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:5:9
  |
5 |         self.consume();
  |         ^^^^ cannot move out of borrowed content

然后团队选择完全明确以保持语法连贯。