Option i32>> { let ret: Option i32>> = match op { -6ren">
gpt4 book ai didi

generics - 返回通用 lambda 时为 "Ambiguous associated type"

转载 作者:行者123 更新时间:2023-11-29 07:54:38 26 4
gpt4 key购买 nike

我有这段代码(人为的,纯粹是实验性的)

fn math_op(op: &str) -> Option<Box<Fn(i32, i32) -> i32>> {
let ret: Option<Box<Fn(i32, i32) -> i32>> = match op {
"+" => Some(Box::new(|a: i32, b: i32| -> i32 { a + b } )),
"-" => Some(Box::new(|a: i32, b: i32| -> i32 { a - b } )),
"*" => Some(Box::new(|a: i32, b: i32| -> i32 { a * b } )),
"/" => Some(Box::new(|a: i32, b: i32| -> i32 { a / b } )),
_ => None,
};

ret
}

它返回一个函数/lambda,它接受两个操作数并返回一个结果(在本例中为加法、减法、除法和乘法运算符)

可以这样调用:

let add: Option<Box<Fn(i32, i32) -> i32>> = math_op("+");
println!("Add {}", add.unwrap()(10, 2));

我真的很想制作一个通用版本,到目前为止我已经...

fn math_op_gen<T>(op: &str) -> Option<Box<Fn(T, T) -> T::Output>> 
where T: std::ops::Add + std::ops::Sub + std::ops::Mul + std::ops::Div {
let ret: Option<Box<Fn(T, T) -> T::Output>> = match op {
"+" => Some(Box::new(|a, b| { a + b } )),
"-" => Some(Box::new(|a, b| { a - b } )),
"*" => Some(Box::new(|a, b| { a * b } )),
"/" => Some(Box::new(|a, b| { a / b } )),
_ => None,
};

ret
}

但是当我构建时出现这些错误:

error: ambiguous associated type `Output` in bounds of `T` [E0221]
note: associated type `T` could derive from `core::ops::Div`
note: associated type `T` could derive from `core::ops::Mul`
note: associated type `T` could derive from `core::ops::Sub`
note: associated type `T` could derive from `core::ops::Add`

我理解这是因为编译器无法根据我实现的各种特征来确定 T::Output 是什么类型。有没有另一种写法来让它工作?

最佳答案

您需要AddSubMulDiv 的输出类型相同。您可以通过添加另一个类型参数并将每个特征的 Output 限制为该类型参数来强制执行此操作。

fn math_op_gen<T, R>(op: &str) -> Option<Box<Fn(T, T) -> R>> 
where T: std::ops::Add<Output=R> +
std::ops::Sub<Output=R> +
std::ops::Mul<Output=R> +
std::ops::Div<Output=R> {
let ret: Option<Box<Fn(T, T) -> R>> = match op {
"+" => Some(Box::new(|a, b| { a + b } )),
"-" => Some(Box::new(|a, b| { a - b } )),
"*" => Some(Box::new(|a, b| { a * b } )),
"/" => Some(Box::new(|a, b| { a / b } )),
_ => None,
};

ret
}

关于generics - 返回通用 lambda 时为 "Ambiguous associated type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192973/

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