请考虑以下代码:
trait Trait<T> {}
fn foo<'a>(_b: Box<dyn Trait<&'a usize>>) {}
fn bar(_b: Box<dyn for<'a> Trait<&'a usize>>) {}
Run Code Online (Sandbox Code Playgroud)
这两个函数foo和bar似乎接受Box<Trait<&'a usize>>,虽然foo比更简明做它bar.他们之间有什么区别?
另外,在什么情况下我需要for<>像上面那样的语法?我知道Rust标准库在内部使用它(通常与闭包有关),但为什么我的代码需要它呢?
我有一个Fibonacci可以用作任何一个迭代器实现结构One,Zero,Add和Clone.这适用于所有整数类型.
我想将这个结构用于BigInteger使用a实现Vec并且调用昂贵的类型clone().我想Add在两个引用上T使用然后返回一个新的T(然后没有克隆).
对于我的生活,我不能制作一个虽然编译的...
工作:
extern crate num;
use std::ops::Add;
use std::mem;
use num::traits::{One, Zero};
pub struct Fibonacci<T> {
curr: T,
next: T,
}
pub fn new<T: One + Zero>() -> Fibonacci<T> {
Fibonacci {
curr: T::zero(),
next: T::one(),
}
}
impl<'a, T: Clone + Add<T, Output = T>> Iterator for Fibonacci<T> {
type Item = T;
fn next(&mut …Run Code Online (Sandbox Code Playgroud) 我有一个特征Matrix和通用功能semi_def<T: Matrix>(x: &T),我想对该特征进行操作。该功能需要一个操作员特征,例如Mul,在上实现T。但是,如果引用之一是对局部变量的引用,我似乎无法使一生愉快。当其中之一只是本地临时引用时,如何在类型约束中编写引用的生存期?
use std::ops::Mul;
trait Matrix: Clone {
fn transpose(self) -> Self;
}
#[derive(Clone)]
struct DenseMatrix {
n_rows: usize,
n_columns: usize,
elements: Vec<f64>,
}
impl Matrix for DenseMatrix {
fn transpose(self) -> Self {
unimplemented!()
}
}
impl<'a, 'b> Mul<&'b DenseMatrix> for &'a DenseMatrix {
type Output = DenseMatrix;
fn mul(self, _rhs: &'b DenseMatrix) -> Self::Output {
unimplemented!()
}
}
fn semi_def<'a, T: Matrix>(x: &'a T) -> T
where
&'a T: …Run Code Online (Sandbox Code Playgroud)