在固有实施的背景下,什么是"名义类型"?

Roo*_*Roo 2 rust

我目前正在浏览Rust文档以了解固有的实现.什么是"名义类型",当他们说"相关项目与实施类型"时,他们指的是什么?

在C或C++中是否存在相关的模拟?

DK.*_*DK. 6

嗯,这是语言参考.学习Rust当然是可能的,但有点像尝试通过阅读字典来学习英语.你试过Rust Book吗?

无论如何,正如第一段所述,"名义类型"是:

impl /* --> */ Point /* <-- this is the "nominal type" */ {
    fn log(&self) { ... }
}
Run Code Online (Sandbox Code Playgroud)

它是固有主体的类型impl.一个"可关联项目"是一个项目(如fn,consttype其与名义类型相关联).

如果你有段落:

我们来谈谈雷蒙德.他的头发是棕色的.他知道如何跳舞.

这大致相当于:

struct Raymond; // introduce the Raymond type.

impl Raymond { // associate some items with Raymond.
    const HAIR: Colour = Colour::Brown;

    fn dance(&mut self) { ... }
}

fn main() {
    let mut ray = Raymond;
    println!("Raymond's hair is {}", Raymond::HAIR);
    ray.dance();
}
Run Code Online (Sandbox Code Playgroud)

(顺便说一句:段落中的代词(如"他"或"他")将会成为selfSelf在其中impl.)

impl这些项目与名义类型相关联.注意HAIRRaymond类型的"内部"是怎样的.您还可以将上面的代码编写为:

struct Raymond;

const RAYMOND_HAIR: Colour = Colour::Brown;

fn raymond_dance(ray: &mut Raymond) { ... }

fn main() {
    let mut ray = Raymond;
    println!("Raymond's hair is {}", RAYMOND_HAIR);
    raymond_dance(&mut ray);
}
Run Code Online (Sandbox Code Playgroud)

这里没有固有的impls,因此RAYMOND_HAIRraymond_dance项目不Raymond直接与类型相关联.除了方便之外,两者之间没有根本区别.

至于把它绑回到C++ ......这很棘手,因为Rust区分了固有的和非固有的impls和C++ ...... 不然.最接近的类比是说它们就像一个struct不是字段的主体部分,而不是基类中的重写方法.