我目前正在浏览 the Rust Documentation了解固有的实现。什么是“标称类型”?当他们说“与实现类型相关的项目”时,他们指的是什么?
在 C 或 C++ 中是否有与此相关的模拟?
最佳答案
嗯,那是语言引用。用它来学习 Rust 当然是可能的,但有点像尝试通过阅读字典来学习英语。你试过Rust Book了吗? ?
无论如何,正如第一段所述,“标称类型”是:
impl /* --> */ Point /* <-- this is the "nominal type" */ {
fn log(&self) { ... }
}
它是固有impl
主题的类型. “关联项目”是与标称类型关联的项目(如 fn
、const
或 type
)。
如果你有段落:
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();
}
(顺便说一句:段落中的代词(如“他”或“他”)将变为 self
或 Self
中的 impl
。)
impl
正在将这些项目与标称类型相关联。注意如何 HAIR
是 Raymond
的“内部”类型。您也可以将上面的代码写成:
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_HAIR
和 raymond_dance
项目与 Raymond
无关直接输入。除了方便之外,两者之间没有根本区别。
至于将其与 C++ 联系起来……这很棘手,因为 Rust 区分固有和非固有 impl
s 和 C++...不会。最接近的类比是说它们就像 struct
的一部分。主体不是字段,也不是重写基类中的方法。
关于rust - 在固有实现的上下文中, "nominal type"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49277733/