【问题标题】:What is the best way to refer to a static method from another static method of the same class in Rust?从 Rust 中同一类的另一个静态方法引用静态方法的最佳方法是什么?
【发布时间】:2018-09-03 15:29:41
【问题描述】:

在一个新的 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 书中看到任何提及这一点,而且我似乎无法在网上找到明确的答案。我可以通过使用myStruct::other() 明确界定对其他人的调用来修复它,但这似乎很麻烦。如果我尝试use myStruct,我会收到神秘信息

7 |     use myStruct;
  |     ^^^ unexpected token

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

我做错了吗?有没有惯用的解决方法?

【问题讨论】:

  • Rust 不像 Java 那样真正是一种“OO”语言。如果你尝试用 Rust 编写 Java,你会遇到很多问题。
  • 这与OO语言没有任何关系,这只是一个关于语法的问题。

标签: module rust static-methods


【解决方案1】:

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

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

【讨论】:

  • 我找不到我所说的任何证据。显式的 self 是在 2012 年实现的:github.com/rust-lang/rust/pull/3974,此时还没有 RFC。
  • 请注意,其他语言(例如 Python)早在 Rust 出现之前就有一个显式的 self 参数,这可能影响了 Rust 的设计。
【解决方案2】:

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

你可以写:

myStruct { x: myStruct::other() }

myStruct { x: Self::other() }

我无法告诉您确切的设计决策,为什么 Self 函数不会自动导入,但您可以通过使用正确的路径“解决”这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    相关资源
    最近更新 更多