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

问题描述 投票:0回答:2

在一个新的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

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

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

module rust static-methods
2个回答
7
投票

Rust设计师做出了以下选择:与范围相关的所有内容都是明确的。因此,正如您必须键入self以从另一个成员函数调用成员函数:self.foo(),您必须使用SelfSelf::bar()调用静态成员。

我认为情况就是这样,因为self不能隐含:实际上它必须通过值或借用作为参数添加,不像在Java中this总是按值获取。因此,因为self已经是一个显式参数,所以需要它作为一致性的显式调用者。

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

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

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


1
投票

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

你可以写:

myStruct { x: myStruct::other() }

要么

myStruct { x: Self::other() }

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

© www.soinside.com 2019 - 2024. All rights reserved.