【发布时间】:2022-12-07 23:51:23
【问题描述】:
如何理解 rust 中的 trait FromWhatever
Rust book 解释如下:
From trait 允许一个类型定义如何从另一个类型创建自己,因此提供了一个非常简单的机制来在多个类型之间进行转换。
听起来很简单。让我们尝试尽可能简单的例子:
use std::str::FromStr; struct MyStructure {} // auto accepted suggestion from language server. impl FromStr for MyStructure { type Err = (); // I've added this fn from_str(_s: &str) -> Result<Self, Self::Err> { Ok(Self {}) // I've added this } } fn main() { const INPUT: &str = "test"; let _tmp: MyStructure = MyStructure::from(INPUT); }Compiling test_range_2 v0.1.0 (/home/pavel/Repositories/test_range_2) error[E0308]: mismatched types --> src/main.rs:15:47 | 15 | let _tmp: MyStructure = MyStructure::from(INPUT); | ----------------- ^^^^^ expected struct `MyStructure`, found `&str` | | | arguments to this function are incorrect | note: associated function defined here --> /home/pavel/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/convert/mod.rs:374:8 | 374 | fn from(_: T) -> Self; | ^^^^ For more information about this error, try `rustc --explain E0308`. error: could not compile `test_range_2` due to previous error所以我期待这种行为:
let target: TARGET_TYPE = TARGET_TYPE::from::<SOURCE_TYPE>(input_var: SOURCE_TYPE);与rust book中的例子相比:
let num = Number::from(30);在我看来,这是一个合理的假设。
但是,阅读错误消息:“expected struct
MyStructure, found&str”。这是否意味着语法是这样的?let target: TARGET_TYPE = TARGET_TYPE::from::<TARGET_TYPE>(input_var: TARGET_TYPE);如果,那是真的,那么 rust book 中的代码也应该失败并出现错误“expected
Number, foundi32”,但事实并非如此。我希望我的解决方案能够工作,因为我已经实现了
trait FromStr,并且我正在尝试从&str创建对象(请参阅“from”和“str”?)。这也是我输入impl FromStr for MyStructure后由语言服务器自动完成的类型。我错过了什么?我想为我的所有类型实现 FromStr,但编译器并不容易。
【问题讨论】:
-
该页面专门指
core::convert::From。FromStr是具有不同方法和期望的不同特征。它们的链接方式不允许您执行MyStructure::from(INPUT)。 -
如果你想使用
From,你为什么要使用FromStr?
标签: rust