首页 > 解决方案 > 从 Rust 中同一类的另一个静态方法引用静态方法的最佳方法是什么?

问题描述

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

struct myStruct {
    x : u32
}

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

    fn other() -> u32 {
        6
    }
}

来自其他 OO 语言,我希望other()new(). 也就是说,我希望能够从同一个类的另一个静态方法调用一个类的一个静态方法。但是, 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 书中看到任何提及这一点,而且我似乎无法在网上找到明确的答案。我可以通过使用 显式限定对 other 的调用来修复它myStruct::other(),但这似乎很麻烦。如果我尝试use myStruct,那么我会收到神秘的信息

7 |     use myStruct;
  |     ^^^ unexpected token

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

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

标签: moduleruststatic-methods

解决方案


Rust 设计者做出了以下选择:与范围相关的所有内容都是明确的。因此,正如您必须键入self才能从另一个成员函数调用成员函数:一样,您必须使用:self.foo()调用静态成员。SelfSelf::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

然后团队选择了完全明确性来保持语法的连贯性。


推荐阅读