在Rust中,是否可以在导入类型时隐式导入特性?

huangapple go评论47阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月24日 19:06:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76753851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定