Generics 如果我';您已经将它们添加到另一个impl块了吗?
我有以下代码:Generics 如果我';您已经将它们添加到另一个impl块了吗?,generics,rust,traits,bounds,Generics,Rust,Traits,Bounds,我有以下代码: use std::ops::Div; use std::ops::Mul; #[derive(Debug)] struct Foo<T> { bar: T, } impl<T> Foo<T> where T: Div<Output = T> + Copy, { fn new(bar: T) -> Foo<T> { let baz = Foo::baz(bar);
use std::ops::Div;
use std::ops::Mul;
#[derive(Debug)]
struct Foo<T> {
bar: T,
}
impl<T> Foo<T>
where
T: Div<Output = T> + Copy,
{
fn new(bar: T) -> Foo<T> {
let baz = Foo::baz(bar);
Foo { bar: bar / baz }
}
fn baz(bar: T) -> T {
unimplemented!();
}
}
impl<T> Mul for Foo<T>
where
T: Mul<Output = T>,
{
type Output = Foo<T>;
fn mul(self, other: Foo<T>) -> Foo<T> {
Foo::new(self.bar * other.bar)
}
}
每个
impl
块彼此完全不同,包括它们的特征边界-一个impl
块具有约束这一事实对其他块没有任何意义
在这种情况下,traitMul
的impl
块实际上并不需要Div
trait,因为它可以直接构造Foo
:
impl<T> Mul for Foo<T>
where
T: Mul<Output = T>,
{
type Output = Foo<T>;
fn mul(self, other: Foo<T>) -> Foo<T> {
Foo { bar: self.bar * other.bar }
}
}
请注意,我说的是“
impl
block”,而不是“固有的impl
block”或“traitimpl
block”。您可以有多个具有不同边界的固有impl
块:
impl<T> Vec<T> {
pub fn new() -> Vec<T> { /* ... */ }
}
impl<T> Vec<T>
where
T: Clone,
{
pub fn resize(&mut self, new_len: usize, value: T) { /* ... */ }
}
impl-Vec{
pub fn new()->Vec{/*…*/}
}
impl-Vec
哪里
T:克隆,
{
pub fn resize(&mut self,new_len:usize,value:T){/*…*/}
}
这允许类型具有仅在满足某些条件时应用的功能
另见:
impl
块彼此完全不同,包括它们的特征边界-一个impl
块具有约束的事实对其他块没有任何意义
在这种情况下,traitMul
的impl
块实际上并不需要Div
trait,因为它可以直接构造Foo
:
impl<T> Mul for Foo<T>
where
T: Mul<Output = T>,
{
type Output = Foo<T>;
fn mul(self, other: Foo<T>) -> Foo<T> {
Foo { bar: self.bar * other.bar }
}
}
请注意,我说的是“
impl
block”,而不是“固有的impl
block”或“traitimpl
block”。您可以有多个具有不同边界的固有impl
块:
impl<T> Vec<T> {
pub fn new() -> Vec<T> { /* ... */ }
}
impl<T> Vec<T>
where
T: Clone,
{
pub fn resize(&mut self, new_len: usize, value: T) { /* ... */ }
}
impl-Vec{
pub fn new()->Vec{/*…*/}
}
impl-Vec
哪里
T:克隆,
{
pub fn resize(&mut self,new_len:usize,value:T){/*…*/}
}
这允许类型具有仅在满足某些条件时应用的功能
另见:
impl<T> Vec<T> {
pub fn new() -> Vec<T> { /* ... */ }
}
impl<T> Vec<T>
where
T: Clone,
{
pub fn resize(&mut self, new_len: usize, value: T) { /* ... */ }
}