Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 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?

See Question&Answers more detail:os

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

1 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...