HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
methodslikeusinginferencetypewhenimpossiblegenericintotrait

Problem

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 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::::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::::into(a)). a.into::() 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?

Solution

You could use From::from:

use std::convert::*;

struct NewType(pub i32);

impl From 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.

Code Snippets

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

Context

Stack Overflow Q#41207885, score: 59

Revisions (0)

No revisions yet.