当然,这只是我实际问题的简化版本。
fn my_func<'a, 'b>(a: &'a i32, b: &'b i32) -> i32 {
a + b
}
fn my_func_generic<'a, 'b, T>(a: &'a T, b: &'b T) -> T
where
&'a T: std::ops::Add<&'b T, Output = T>,
{
a + b
}
fn apply_function(x: &i32, y: &i32, function: fn(&i32, &i32) -> i32) -> i32 {
function(x, y)
}
fn main() {
let x = 10;
let y = 11;
println!("{}", my_func(&x, &y));
println!("{}", my_func_generic(&x, &y));
println!("{}", apply_function(&x, &y, my_func));
println!("{}", apply_function(&x, &y, my_func_generic));
}
error[E0308]: mismatched types
--> src/main.rs:23:43
|
23 | println!("{}", apply_function(&x, &y, my_func_generic));
| ^^^^^^^^^^^^^^^ one type is more general than the other
|
= note: expected fn pointer `for<'r, 's> fn(&'r i32, &'s i32) -> _`
found fn pointer `fn(&i32, &i32) -> _`
我有一个问题:如何将
my_func_generic
用作函数指针传递给apply_function
?它绝对可以作为这样的函数使用,正如
println!("{}", my_func_generic(&x, &y))
所示。尝试将其写成指针会产生相同的错误:
let function_pointer: fn(&i32, &i32) -> i32 = my_func_generic;
手动注释泛型类型会出现相同的错误:
let function_pointer: fn(&i32, &i32) -> i32 = my_func_generic::<'_, '_, i32>;
很遗憾,我不理解这个错误信息,并且对于Rust泛型内部类型系统的知识不够,无法理解如何解决这个问题,或者是否由于某些机制的未知原因而根本不可能解决。
fn apply_function<'a, 'b, 'a2, 'b2>(x: &'a i32, y: &'b i32, function: fn(&'a2 i32, &'b2 i32) -> i32) -> i32 where 'a: 'a2, 'b: 'b2
?playground - rodrigo'a : 'a2
是不是多余的?因为你可以直接使用'a
。 - Finomnisapply_function()
调用了function(x, y) + function(y, x)
,那么 ChayimFiredman 的解决方案将不起作用,但我的解决方案where 'a: 'a2 + 'b2, 'b: 'a2 + 'b2
将会奏效。 - rodrigo