【问题标题】:Provide explicit type specification despite `impl Trait` argument尽管有 `impl Trait` 参数,但仍提供显式类型规范
【发布时间】:2020-08-23 08:12:36
【问题描述】:

考虑以下最小示例:

fn foo<T>(arg: T, f: impl FnOnce(i32) -> i32) -> Vec<T> {
   let mut x: Vec<T> = Vec::new();
   x.push(arg);
   println!("{:?}", f(5));
   x   
} 

fn main() {
   println!("{:?}", foo::<u32>(5, |i_arg| { i_arg + 5 }));
}

因为使用了impl Trait而无法编译:

error[E0632]: cannot provide explicit generic arguments when `impl Trait` is used in argument position
  --> src/main.rs:10:28
   |
10 |     println!("{:?}", foo::<u32>(5, |i_arg| { i_arg + 5 }));
   |                            ^^^ explicit generic argument not allowed

error: aborting due to previous error

error: could not compile `generic_functions`.

尽管在另一个参数中使用了impl Trait,我是否有可能为T 指定类型?我在一个代码库中工作,我需要调用一个使用impl Trait 的泛型函​​数,但我需要指定其他泛型类型。

【问题讨论】:

    标签: generics rust numbers closures traits


    【解决方案1】:

    从您的示例中,我不明白您为什么要尝试使用涡轮鱼。 T 的类型可以从输入参数arg 确定。无论您以 arg 的形式传入什么,编译器都会推断出 T 是什么。我更新了你的例子来工作:

    fn foo<T>(arg: T, f: impl FnOnce(i32) -> i32) -> Vec<T> {
       let mut x: Vec<T> = Vec::new();
       x.push(arg);
       println!("{:?}", f(5));
       x   
    } 
    
    fn main() {
       println!("{:?}", foo(5u32, |i_arg| { i_arg + 5 }));
    }
    

    playground

    【讨论】:

    • 感谢您的回复-问题是,我处于一个显然无法从输入参数 arg 确定类型的设置中-该代码相当复杂,我将尝试提供一个示例这说明了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2020-04-06
    • 2021-12-30
    • 2021-02-01
    • 2017-08-22
    • 1970-01-01
    • 2015-12-26
    相关资源
    最近更新 更多