[英]rust - return type from generic function with traits
I'm trying to understand how generic functions works in Rust.我试图了解通用函数在 Rust 中是如何工作的。 Here's my code:
这是我的代码:
fn evaluate<T: std::ops::Mul>(portfolio: T, quote: T) -> T {
portfolio * quote
}
And I getting the error:我收到错误:
error[E0308]: mismatched types
--> src/main.rs:10:5
|
9 | fn evaluate<T: std::ops::Mul>(portfolio: T, quote: T) -> T {
| - expected `T` because of return type
10 | portfolio * quote
| ^^^^^^^^^^^^^^^^^ expected type parameter `T`, found associated type
|
= note: expected type parameter `T`
found associated type `<T as std::ops::Mul>::Output`
= note: you might be missing a type parameter or trait bound
What i'm doing wrong?我在做什么错?
Rust does not assume that multiplication of to values of type T
always results in a new value of type T
.锈不承担对类型的值乘法
T
总是导致类型的新值T
。 Instead, the Mul
trait has an associated type Output
that specifies the return type of the multiplication.相反,
Mul
trait 有一个关联的类型Output
,它指定乘法的返回类型。 The error message mentions that type as "found associated type <T as std::ops::Mul>::Output
".错误消息提到该类型为“找到关联类型
<T as std::ops::Mul>::Output
”。 So the easiest solution is to change the return type of your function to the assoicated type:因此,最简单的解决方案是将函数的返回类型更改为关联类型:
fn evaluate<T: std::ops::Mul>(portfolio: T, quote: T) -> <T as std::ops::Mul>::Output {
portfolio * quote
}
A common example where Output
does not match the input type is multiplying two references – the output will usually be an owned type, not a reference again. Output
与输入类型不匹配的一个常见示例是将两个引用相乘——输出通常是一个拥有的类型,而不是再次引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.