[英]How do I bound a generic type with a trait that requires a lifetime parameter if I create the reference inside the function?
I want to implement a generic fibonacci
function that works with any type implementing Zero
, One
, and AddAssign
. 我想实现一个通用的
fibonacci
函数,该函数可与实现Zero
, One
和AddAssign
任何类型AddAssign
。 I first implemented a version that works fine, but is specialized for num::BigUint
( see on play.rust-lang.org ). 我首先实现了一个工作正常的版本,但专门用于
num::BigUint
( 请参见play.rust-lang.org )。 I than came up with the following generic implementation ( see on play.rust-lang.org ): 然后,我提出了以下通用实现( 请参见play.rust-lang.org ):
extern crate num;
use num::{One, Zero};
use std::mem::swap;
use std::ops::AddAssign;
fn fib<T: Zero + One + AddAssign<&T>>(n: usize) -> T {
let mut f0 = Zero::zero();
let mut f1 = One::one();
for _ in 0..n {
f0 += &f1;
swap(&mut f0, &mut f1);
}
f0
}
This doesn't compile: 这不会编译:
error[E0106]: missing lifetime specifier
--> src/main.rs:7:34
|
7 | fn fib<T: Zero + One + AddAssign<&T>>(n: usize) -> T {
| ^ expected lifetime parameter
Rust wants me to add a lifetime parameter to AddAssign<&T>
but I don't know how to express the lifetime of f1
. Rust希望我向
AddAssign<&T>
添加一个生命周期参数,但是我不知道如何表达f1
的生命周期。
You need to use Higher Rank Trait Bounds . 您需要使用较高等级特质界限 。 This one means basically "For any lifetime
'a
, T
satisfies the AddAssign<&'a T>
trait": 这基本上意味着“对于任何生命
'a
, T
满足AddAssign<&'a T>
特性”:
fn fib<T>(n: usize) -> T
where
for<'a> T: Zero + One + AddAssign<&'a T>,
I also had to change the way fib
is called because the compiler couldn't figure out the return type, which could be literally any type that implements those traits. 我还必须更改
fib
的调用方式,因为编译器无法弄清楚返回类型,返回类型实际上可以是实现这些特征的任何类型。 Declaring x
's type gives sufficient context to the compiler so that it knows what you want. 声明
x
的类型为编译器提供了足够的上下文,以便它知道您想要什么。
fn main() {
let x: num::BigUint = fib(10);
// let x = fib::<BigUint>(10); // Also works
println!("fib(10) = {}", x);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.