我什么时候应该实现std :: convert :: From vs std :: convert :: Into?

Shepmaster

我看到std::convert::Into对于任何实现的东西都有一个实现std::convert::From

impl<T, U> Into<U> for T
where
    U: From<T>, 

在Rust 1.0标准库中,Fromwhile的许多实现Into仅在3个地方实现。这使得实现似乎From是默认设置。我确定有些时候我想实现Into而不是From,但是我没有看到它们。

遇见

TL; DR:更喜欢实施From


有趣的是,有关特征的原始RFCstd::convert提出了完全相反的实现:

impl<T, U> From<T> for U
where
    T: Into<U>

但是在PR实施时,它变成了相反的样子

添加了From=>Into实现,这使得可以在两个方向上添加转换而不会产生一致性。例如,我们现在有了From<[T]> for Vec<T>where T: Clone,它会产生Into另一个方向的对应变化-尽管这两种类型生活在不同的板条箱中。

我还认为,这解决了一些有关实施的担忧,From而不是Into

最后时刻的变化反映了这一点FromInto并且基本上是等效的。From之所以选择它作为首选,是因为从“类型参数与本地类型”的角度来看,限制较少。

Rust 1.41.0之前,不可能创建impl<'a, T> Into<Foo> for &'a [T],而impl<'a, T> From<&'a [T]> for Foo可能。

第一次尝试提出了E0210

error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
 --> x.rs:3:10
  |
3 | impl<'a, T> Into<Foo> for &'a [T] {
  |          ^ type parameter `T` must be used as the type parameter for some local type
  |
  = note: only traits defined in the current crate can be implemented for a type parameter

在Rust 1.14之前的标准库中,只有两个实现示例,Into而没有From

  • impl Into<Vec<u8>> for String
  • impl Into<OsString> for PathBuf

我认为这是对接口逻辑的反思。OsString实现From<String>From<T> where T: AsRef<OsStr>,因为它们是您想要构建的自然对象OsString

但是,PathBufInto<OsString>作为其From<OsString>实现的反向操作实现,但是此逻辑属于PathBuf,而不是OsString

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我们什么时候应该使用std :: enable_shared_from_this

未实现特征`std :: convert :: From <cli :: Opts>`

我什么时候应该使用std :: any

我什么时候应该std :: forward函数调用?

我什么时候应该使用std :: thread :: detach?

我什么时候应该返回std :: ostream?

如何解决hyper :: Body的特性std :: convert :: From <serde_json :: Value>没有实现?

性状std :: convert :: From <String>不适用于hyper :: body :: Body

什么是std :: decay,什么时候应该使用?

什么时候应该使用std :: thread :: joinable?

如何在Rust中的语句中使用std :: convert :: Into?

什么时候应该使用std :: thread :: Builder而不是std :: thread :: spawn?

什么时候应该使用std :: string / std :: string_view作为参数/返回类型

我什么时候应该使用hstack / vstack vs append vs concatenate vs column_stack

什么时候执行std :: future?

什么时候std :: chrono时代?

我什么时候应该删除从正则表达式迭代器内的 std::smatch 返回的 std::string ,如果有的话?

在C ++ 11中,什么时候应该显式使用std :: decay?

什么时候应该在函数返回值上使用std :: move?

std :: function vs template

QThread vs std :: thread

EmberJS:我什么时候应该使用Torii vs Ember-Simple-Auth?

React Context vs React Redux,我什么时候应该使用每一个?

我什么时候应该使用dt.column vs dt ['column']大熊猫?

nodejs:我什么时候应该使用`setImmediate(cb)`vs`cb()`?

Couchbase-我什么时候应该使用N1QL vs Views?

尝试写入 CSV 记录时出现错误“特性 `std::convert::AsRef<[u8]>` 未为 `u8` 实现”

impl convert :: From for(mutable)reference

Getitem vs Iter&Next。什么时候应该使用?