How to use std::convert::Into in statements in Rust? [duplicate]

﹥>﹥吖頭↗ 提交于 2020-02-25 02:59:05

问题


I am trying to use into in the following code this way:

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);
}

It produces an error:

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

I have tried s.into::<i64>() and s.into<i64>() without any success. The only case that worked was let y: i64 = s.into();, but I need into() in statements. What is the correct use of into?


回答1:


Note: according to the documentation, you should not impl Into yourself; instead write a From for the reverse types and use the blanket implementation.

impl From<MyStruct> for i64 {
    fn from(a: MyStruct) -> i64 {
        a.x
    }
}

Now, as for the call, if you want to explicitly qualify the call, you must use the universal call syntax:

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

Alternatively, you can put the into into a context where the result type is known:

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

Or if you're on nightly, you can use inline type ascription by enabling the experimental feature; put #![feature(type_ascription)] at the top of your file:

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

One more option that works on stable, if for some reason you find the universal call syntax impossible to swallow (IMO this one is uglier, but it's a matter of taste). Since blocks in Rust are expressions, you can write

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

Also note, you need into in expressions, not statements.



来源:https://stackoverflow.com/questions/54435616/how-to-use-stdconvertinto-in-statements-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!