From :: from和Rust中的as有什么区别? [英] What is the difference between From::from and as in Rust?
问题描述
我可以使用 from
或 as
as
I can cast between types by using either from
or as
:
i64::from(42i32);
42i32 as i64;
两者之间有什么区别?
推荐答案
as
仅可用于固定的小型转换集。 参考文件 as
:
as
can only be used in a small, fixed set of transformations. The reference documents as
:
as
用于显式执行强制,以及
跟随其他演员。在这里* T
表示* const T
或* mut T
。
as
can be used to explicitly perform coercions, as well as the following additional casts. Here*T
means either*const T
or*mut T
.
| Type of `e` | `U` | Cast performed by `e as U` |
|-----------------------+-------------------------+----------------------------------|
| Integer or Float type | Integer or Float type | Numeric cast |
| C-like enum | Integer type | Enum cast |
| `bool` or `char` | Integer type | Primitive to integer cast |
| `u8` | `char` | `u8` to `char` cast |
| `*T` | `*V` where `V: Sized` * | Pointer to pointer cast |
| `*T` where `T: Sized` | Numeric type | Pointer to address cast |
| Integer type | `*V` where `V: Sized` | Address to pointer cast |
| `&[T; n]` | `*const T` | Array to pointer cast |
| Function pointer | `*V` where `V: Sized` | Function pointer to pointer cast |
| Function pointer | Integer | Function pointer to address cast |
| Closure ** | Function pointer | Closure to function pointer cast |
* or `T` and `V` are compatible unsized types, e.g., both slices, both the
same trait object.
** only for closures that do not capture (close over) any local variables
由于 as
对于编译器是已知的,并且仅对某些转换有效,因此它可以执行某些类型的更复杂的转换。
Because as
is known to the compiler and only valid for certain transformations, it can do certain types of more complicated transformations.
From
是一个特征,这意味着任何程序员都可以针对自己的类型实现它,从而可以在更多情况下使用它。它与 进入
。 TryFrom
和 TryInto
自Rust 1.34起一直稳定。
From
is a trait, which means that any programmer can implement it for their own types and it is thus able to be applied in more situations. It pairs with Into
. TryFrom
and TryInto
have been stable since Rust 1.34.
由于它是一个特征,因此可以在通用上下文中使用( fn foo(名称:impl Into< String>){/ * ... * /}
)。对于 as
,这是不可能的。
Because it's a trait, it can be used in a generic context (fn foo(name: impl Into<String>) { /* ... */ }
). This is not possible with as
.
在数字类型之间进行转换时,需要注意的是 From
仅用于无损转换(例如,您可以从 i32
转换为 i64
和 From
,但并非相反),而 as
适用于无损和有损转换(如果转换是有损的,则会截断)。因此,如果要确保您不会意外执行有损转换,则可能更喜欢使用 From :: from
而不是 as
。
When converting between numeric types, one thing to note is that From
is only implemented for lossless conversions (e.g. you can convert from i32
to i64
with From
, but not the other way around), whereas as
works for both lossless and lossy conversions (if the conversion is lossy, it truncates). Thus, if you want to ensure that you don't accidentally perform a lossy conversion, you may prefer using From::from
rather than as
.
另请参见:
- When should I implement std::convert::From vs std::convert::Into?
这篇关于From :: from和Rust中的as有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!