我有模块mod1.rs:
pub struct Foo;
impl Foo {}
impl Drop for Foo {
fn drop(&mut self) {}
}
在 file2.rs 我写了 use mod1::Foo;
。
我在 file2.rs 中实际上有什么?只有
struct Foo
,impl Foo
?impl Drop for Foo
怎么样?如果我在 file2.rs 中获得了
Foo
的所有特征,然后我写fn my_func(foo: Foo)...
,我这里有什么?Foo
是struct
还是特征 (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 aboutimpl Drop for Foo
?
当您使用
结构或枚举等类型时,您将获得所有固有方法;在 impl Foo
中定义的那些。您还可以访问该类型的任何公共(public)字段。
If I get all traits for
Foo
in file2.rs, and I writefn my_func(foo: Foo)
, what do I have here? IsFoo
a struct or a trait (impl Foo
) here?
impl Foo
不是 trait。 trait Bar
定义一个特征。 impl Bar for Foo
为 Foo
类型实现一个特征。 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 byuse 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/