From :: from和Rust之间有什么区别?

问题描述 投票:3回答:1

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

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

那些有什么区别?

casting rust
1个回答
8
投票

as只能用于一组固定的小型转换。 The reference documents as

as可用于明确执行coercions,以及以下额外的演员阵容。在这里*T意味着*const T*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 |

†或TV是兼容的未定义类型,例如两个切片,两者都是相同的特征对象。

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

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

因为它是一个特征,它可以在通用上下文中使用(fn foo<S: Into<String>(name: S) { /* ... */})。这与as无法实现。

在数值类型之间进行转换时,有一点需要注意的是From仅用于无损转换(例如,您可以使用i32i64转换为From,但不是相反),而as适用于无损转换和有损转换(如果转换是有损的,它会截断)。因此,如果您想确保不会意外地执行有损转换,您可能更喜欢使用From::from而不是as

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.