as
只能用于一小部分固定的变换.The reference documents as
:
as
可用于显式执行coercions,如下所示:
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
orchar
Integer type Primitive to integer cast u8
char
u8
tochar
cast*T
*V
whereV: Sized
*Pointer to pointer cast *T
whereT: Sized
Numeric type Pointer to address cast Integer type *V
whereV: Sized
Address to pointer cast &[T; n]
*const T
Array to pointer cast Function item Function pointer Function item to function pointer cast Function item *V
whereV: Sized
Function item to pointer cast Function item Integer Function item to address cast Function pointer *V
whereV: Sized
Function pointer to pointer cast Function pointer Integer Function pointer to address cast Closure ** Function pointer Closure to function pointer cast *或
T
和V
是兼容的非尺寸类型,例如,两个切片,两个**仅适用于不捕获(关闭)任何局部变量的闭包
因为编译器知道as
,并且只对某些转换有效,所以它可以执行某些类型的更复杂的转换.
From
is a trait,这意味着任何程序员都可以为自己的类型实现它,因此可以应用于更多情况.它与Into
配对.TryFrom
和TryInto
自 rust 1.34以来一直稳定.
因为它是一种trait ,所以可以在一般语境中使用(fn foo(name: impl Into<String>) { /* ... */ }
).对于as
,这是不可能的(尽管参见num crate 中的AsPrimitive
).
在数字类型之间进行转换时,需要注意的一点是,From
只适用于lossless conversions(例如,可以使用From
从i32
转换为i64
,但不能反过来),而as
适用于无损和有损转换(如果转换是有损的,则会截断).因此,如果您想确保不会意外执行有损转换,您可能更喜欢使用From::from
而不是as
.
另见: