gpt4 book ai didi

generics - 尽管提供了 `impl Trait`参数,但仍提供了明确的类型规范

转载 作者:行者123 更新时间:2023-12-03 11:43:13 24 4
gpt4 key购买 nike

请考虑以下最小示例:

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`.

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

最佳答案

从您的示例中,我不明白您为什么要尝试使用turbofish。 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

关于generics - 尽管提供了 `impl Trait`参数,但仍提供了明确的类型规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61667833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com