如何在 Rust 中的语句中使用 std::convert::into

  • 本文关键字:std convert into 语句 Rust rust
  • 更新时间 :
  • 英文 :


我正在尝试以这种方式在以下代码中使用into

use std::convert::{From, Into};
struct MyStruct {
    x: i64,
}
impl From<i64> for MyStruct {
    fn from(a: i64) -> Self {
        Self { x: a }
    }
}
impl Into<i64> for MyStruct {
    fn into(self) -> i64 {
        self.x
    }
}
fn main() {
    let s = MyStruct::from(5);
    let b = s.into() == 5;
    println!("{:?}", b);
}

它会产生一个错误:

error[E0283]: type annotations required: cannot resolve `MyStruct: std::convert::Into<_>`
  --> src/main.rs:21:15
   |
21 |     let b = s.into() == 5;
   |               ^^^^

我尝试过s.into::<i64>()s.into<i64>(),但没有任何成功。唯一有效的案例是 let y: i64 = s.into(); ,但我需要在语句中into()into的正确用法是什么?

注意:根据文档,你不应该自己impl Into;而是为反向类型编写一个From并使用一揽子实现。

impl From<MyStruct> for i64 {
    fn from(a: MyStruct) -> i64 {
        a.x
    }
}
现在,对于调用,

如果要显式限定调用,则必须使用通用调用语法:

fn main() {
    let s = MyStruct::from(5);
    let b = Into::<i64>::into(s) == 5;
    println!("{:?}", b);
}

或者,您可以将into放入结果类型已知的上下文中:

fn main() {
    let s = MyStruct::from(5);
    let i: i64 = s.into();
    let b = i == 5;
    println!("{:?}", b);
}

或者,如果您每晚使用,则可以通过启用实验性功能来使用内联类型归因;将#![feature(type_ascription)]放在文件的顶部:

fn main() {
    let s = MyStruct::from(5);
    let b = (s.into(): i64) == 5;
    println!("{:?}", b);
}

另一个适用于稳定版的选项,如果由于某种原因您发现通用调用语法无法吞咽(IMO 这个更丑陋,但这是一个品味问题)。由于 Rust 中的块是表达式,因此您可以编写

fn main() {
    let s = MyStruct::from(5);
    let b = { let t: i64 = s.into(); t } == 5;
    println!("{:?}", b);
}

另请注意,您需要在表达式into,而不是语句。

相关内容

最新更新