英文:
Is it possible to implicitly import traits when importing a type in Rust?
问题
有一些已经编写的文件定义了一个类型。对于这个类型实现了一些特质。
在使用 use TYPE_X
导入该类型时,是否可以隐式导入为 TYPE_X
实现的特质?
例如,FromStr
是一个特质,要调用 TYPE_X::from_str()
,需要在所有地方显式导入 std::str::FromStr
。这有些不方便,特别是在这种情况下,需要导入多个特质才能使用单一类型。
英文:
There are some files which have been written which define a type. Some traits are implemented for this type.
When importing the type with use TYPE_X
is it possible to implicitly import the Traits which are implemented for TYPE_X
?
For example, FromStr
is a trait which requires explicitly importing std::str::FromStr
everywhere in order to call TYPE_X::from_str()
. This is somewhat inconvenient and in this particular case results in importing several traits just to be able to use a single type.
答案1
得分: 2
这是不可能的。
你可以做的最接近的方法是将类型和特性放置(或重新导出)到某个模块中,并从中进行全局导入(use module::*
)。但通常不建议使用全局导入。
英文:
No, this is not possible.
The closest you can do is place (or reexport) the type and the trait from some module and glob-import from it (use module::*
). However glob imports are generally discouraged.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论