rust - 如何在 Rust 的语句中使用 std::convert::Into?

标签 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 中的 block 是表达式,您可以这样写

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

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

关于rust - 如何在 Rust 的语句中使用 std::convert::Into?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54435616/

相关文章:

loops - 发生错误时循环的正确方法是什么

multithreading - 无法将数据移出 Mutex

rust - 为什么不可变字符串可以调用 String::add(mut self, other: &str)

asynchronous - 如何在 Rust 中返回一个返回特征的函数

rust - 字符串到解析值的向量

rust - 如何在 Rust 的变量中存储模式?

rust - 如何将可变引用传递给属于该引用的对象上的方法?

rust - 如何以独立于平台的方式将 "./"添加到路径?

rust - 在实现返回可变引用的迭代器时,如何修复 “cannot infer an appropriate lifetime for autoref”?

rust - 使用HashMap实现在迭代器上映射的函数的生命周期问题