我可以使用fromas在类型之间转换:

i64::from(42i32);
42i32 as i64;

这两者有什么区别?

推荐答案

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 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 item Function pointer Function item to function pointer cast
Function item *V where V: Sized Function item to pointer cast
Function item Integer Function item to address 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

*或TV是兼容的非尺寸类型,例如,两个切片,两个

**仅适用于不捕获(关闭)任何局部变量的闭包

因为编译器知道as,并且只对某些转换有效,所以它可以执行某些类型的更复杂的转换.

From is a trait,这意味着任何程序员都可以为自己的类型实现它,因此可以应用于更多情况.它与Into配对.TryFromTryInto自 rust 1.34以来一直稳定.

因为它是一种trait ,所以可以在一般语境中使用(fn foo(name: impl Into<String>) { /* ... */ }).对于as,这是不可能的(尽管参见num crate 中的AsPrimitive).

在数字类型之间进行转换时,需要注意的一点是,From只适用于lossless conversions(例如,可以使用Fromi32转换为i64,但不能反过来),而as适用于无损和有损转换(如果转换是有损的,则会截断).因此,如果您想确保不会意外执行有损转换,您可能更喜欢使用From::from而不是as.

另见:

Rust相关问答推荐

在actix—web中使用Redirect或NamedFile响应

使用Rust s serde_json对混合数据类型进行优化'

当一个箱子有自己的依赖关系时,两个人如何克服S每箱1库+n箱的限制?

重写Rust中的方法以使用`&;mut self`而不是`mut self`

是否可以在不切换到下一个位置的情况下获得迭代器值:

写入引用会更新基础值,但引用会打印意外的值

Const 上下文:从 init 函数创建具有 const 通用长度的数组

返回优化后的标题:返回异步块的闭包的类型擦除

没有明确地说return会产生错误:match arms have incompatible types

不安全块不返回预期值

在 Rust 中,我如何处理请求 javascript 的页面?

特征中定义的类型与一般定义的类型之间的区别

如何展平以下嵌套的 if let 和 if 语句?

Rust 将特性传递给依赖项

SDL2 没有在终端键上触发?

第 7.4 章片段中如何定义 `thread_rng`

从 Cranelift 发出 ASM

为什么这里需要类型注解?

为什么 u64::trailing_zeros() 在无分支工作时生成分支程序集?

如果参数为 Send,则返回 Future Send