rust - 为什么标准库要实现从每种类型到自身的转换?

标签 rust type-conversion identity traits

Programming Rust 的第 298 页可以找到如下语句

The standard library automatically implements the trivial conversion from each type to itself: every type T implements From<T> and Into<T>

但是它实际上并没有说明为什么这会有用,或者为什么标准库会自动这样做?这是什么原因?

最佳答案

在编写带有泛型参数的函数/类型时会很方便。例如,如果我写一个函数:

fn do_something_with_string<S: Into<String>>(s: S) {}

该函数同样适用于 String 和任何可以变成一个的东西。

关于rust - 为什么标准库要实现从每种类型到自身的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58089386/

相关文章:

ios - 如何在iPCU中设置MDM Payload的 "Identity"?

enums - 有没有办法在 Rust 中使用 "flatten"枚举进行(反)序列化?

javascript - 为什么新对象 ("foo") 返回 "[object Object]"

mysql - 转换varchar值时转换失败

sql-server - SQL Server : how can I get the correct DB size from sys. master_files?

java - 有没有我可以使用的 Map 来防止 .equals() 重复?

ASP.net 身份教程

带有 arg 函数的 Rust 函数

asynchronous - Rust 中单线程异步应用程序的高效同步原语

Rust 中的特征和实现