当无法进行类型推断时,使用 .into() 等通用 trait 方法 [英] Using generic trait methods like .into() when type inference is impossible

查看:18
本文介绍了当无法进行类型推断时,使用 .into() 等通用 trait 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用 .into() 在无法进行类型推断的上下文中转换值.这通常是当我想将临时值转换为其他类型以将其传递给通用函数时.请参阅以下代码示例(playground):

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
}

我收到错误:

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

如何正确告诉编译器我想将 a 转换为 i32?

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

我可以通过将类型参数显式提供给 Into 使其正常工作:Into::<i32>::into(a).这比我希望能够实现的更加冗长和明确,尤其是在我没有导入 Into (std::convert::Into::<i32>::进入(a)).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 看起来不错,但这种确切的语法不起作用.

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

我缺少什么技巧吗?

推荐答案

你可以使用 From::from:

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.

这篇关于当无法进行类型推断时,使用 .into() 等通用 trait 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆