rust - 在固有实现的上下文中, "nominal type"是什么?

标签 rust

我目前正在浏览 the Rust Documentation了解固有的实现。什么是“标称类型”?当他们说“与实现类型相关的项目”时,他们指的是什么?

在 C 或 C++ 中是否有与此相关的模拟?

最佳答案

嗯,那是语言引用。用它来学习 Rust 当然是可能的,但有点像尝试通过阅读字典来学习英语。你试过Rust Book了吗? ?

无论如何,正如第一段所述,“标称类型”是:

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

它是固有impl 主题的类型. “关联项目”是与标称类型关联的项目(如 fnconsttype)。

如果你有段落:

Let's talk about Raymond. His hair is brown. He knows how to dance.

这大致相当于:

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();
}

(顺便说一句:段落中的代词(如“他”或“他”)将变为 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);
}

这里没有固有的impl s,所以 RAYMOND_HAIRraymond_dance项目与 Raymond 无关直接输入。除了方便之外,两者之间没有根本区别。

至于将其与 C++ 联系起来……这很棘手,因为 Rust 区分固有和非固有 impl s 和 C++...不会。最接近的类比是说它们就像 struct 的一部分。主体不是字段,也不是重写基类中的方法。

关于rust - 在固有实现的上下文中, "nominal type"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49277733/

相关文章:

rust - 在 Result<Option<T>> 的情况下简化 Rust 中的错误处理

rust - 处理可能是驱动器号或连接到其他路径的路径的正确方法是什么?

rust - 如何以简单的英语引用 SPI1 数据寄存器以在 Rust 中设置 DMA

rust - 如何在 Rust 中转储完整的编译器属性列表?

rust - "cannot move out of index of"是什么意思?

rust - 在 Rust 特征中公开实现细节

command-line - 给定 rust 中的绝对路径,如何上传文件?

rust - 这个 "atomic"Rust 代码和对应的 "non-atomic"代码有什么区别?

web-scraping - 如何使用 scraper crate 获取元素的内部文本?

rust - 通过 Rumble 从 Bluetooth 5 LE DevBoard 读取串行数据流