可以避免在'impl'函数体中重复结构名称?

ide*_*n42 3 rust

可以Self在一个impl块内使用:

impl SomeStruct {
    pub fn new() -> Self {
        SomeStruct { foo: 1, bar: 1, }
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在函数体中引用类型?例如:

impl SomeStruct {
    pub fn new() -> Self {
        Self { foo: 1, bar: 1, }
    //  ^^^^ not recognized, possibly there is some alternative?
    }
}
Run Code Online (Sandbox Code Playgroud)

这不是必需的,只能在可以推断时避免重复长结构名称.它也可能对生成的代码很有用.

Luk*_*odt 7

Rust 1.16开始,您的代码编译得很好!的Self关键字现在可以在多个位置上被使用,包括结构表达式和impl报头.

相关链接: