Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

rust - Using generic trait methods like .into() when type inference is impossible

I'm hoping to be able to use .into() to convert a value in a context where type inference is impossible. This is typically when I want to convert a temporary value into some other type for passing it into a generic function. See the following code for an example (playground):

use std::convert::*;

struct NewType(pub i32);

impl From<NewType> for i32 {
    fn from(src: NewType) -> i32 {
        src.0
    }
}

fn main() {
    let a = NewType(5);
    println!("{}", a.into()); // Understandably won't compile
}

I get the error:

error[E0282]: type annotations needed
  --> src/main.rs:13:20
   |
13 |     println!("{}", a.into());
   |                    ^^^^^^^^ cannot infer type for `T`

How do I properly tell the compiler that I want to convert a into i32?

I can get it to work right by explicitly feeding Into with type arguments: Into::<i32>::into(a). This is more verbose and explicit than I was hoping to be able to achieve, especially in a context where I have not imported Into (std::convert::Into::<i32>::into(a)). a.into::<i32>() would be acceptable, but that is not where the type arguments go.

a.into() as i32 would look nice, but this exact syntax doesn't work.

Is there a trick I am missing?

question from:https://stackoverflow.com/questions/41207885/using-generic-trait-methods-like-into-when-type-inference-is-impossible

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use From::from:

use std::convert::*;

struct NewType(pub i32);

impl From<NewType> for i32 {
    fn from(src: NewType) -> i32 {
        src.0
    }
}

fn main() {
    let a = NewType(5);
    println!("{}", i32::from(a));
}

You can read more about it in the docs for the convert module.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...