rust - 当我使用来自另一个模块的结构时导入了什么?

标签 rust

我有模块mod1.rs:

pub struct Foo;

impl Foo {}

impl Drop for Foo {
    fn drop(&mut self) {}
}

file2.rs 我写了 use mod1::Foo;

  1. 我在 file2.rs 中实际上有什么?只有struct Fooimpl Fooimpl Drop for Foo 怎么样?

  2. 如果我在 file2.rs 中获得了 Foo 的所有特征,然后我写 fn my_func(foo: Foo)...,我这里有什么? Foostruct 还是特征 (impl Foo)?

我读了 Rust 书和手册,但他们只解释 显式使用,更不用说使用相同名称 (impl) 的 trait 会发生什么。 Rust 书告诉您显式导入特征,如果是这样并且 Drop 不是通过 use mod1::Foo 导入的,这是一件非常非常糟糕的事情。

最佳答案

In file2.rs I wrote use mod1::Foo;.

What do I actually have in file2.rs? Only struct Foo, impl Foo? What about impl Drop for Foo?

当您使用结构或枚举等类型时,您将获得所有固有方法;在 impl Foo 中定义的那些。您还可以访问该类型的任何公共(public)字段。

If I get all traits for Foo in file2.rs, and I write fn my_func(foo: Foo), what do I have here? Is Foo a struct or a trait (impl Foo) here?

impl Foo 不是 traittrait Bar 定义一个特征。 impl Bar for FooFoo 类型实现一个特征。 impl Foo 创建固有方法;这些与特征无关。

I read the Rust book and manual, but they explain only explicit usage, not mention what happens with trait with the same name (impl). The Rust book tells you to import traits explicitly, if so and Drop is not imported by use mod1::Foo, this is a really, really bad thing.

对于语言设计者来说,这将是一个非常糟糕的主意。值得庆幸的是,他们没有那样做。导入某些东西只是允许导入它的代码使用它。如果不导入,不会导致代码消失。

编译器本身是实现Drop 的类型的用户,因此您可以将其视为编译器实现在某处use Drop。这可能不是字面上是真的,而是一种心智模型。仅仅因为您的代码不导入 Drop 并不意味着其他代码不能导入。

如其他地方所述,您不必导入 Drop,因为它是 included in the prelude .

关于rust - 当我使用来自另一个模块的结构时导入了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38343742/

相关文章:

casting - 如何检查 'Box<Any>' 是否包含短表达式中的 'Unit'?

rust - 如何在不实例化的情况下在 Rust 中获取结构字段的大小

rust - Rust/Rocket中的POST声明有问题

rust - 如何不借钱就能确保 self 超越返回值(value)

rust - 将特征方法和关联类型标记为特化的默认值时预期输出类型发生变化

100字节内存分配失败

rust - 为什么 `ref` 会导致此示例*取消引用*一个字段?

string - 在不收集的情况下迭代字符串的窗口

rust - Rust 中的可变Arc

rust - 不能借用 `...` 作为可变的,因为它也被借用为不可变的