在Rust中实现了Default trait 则为类型设定了默认值。有时默认值还是挺有用的。下面看一下定义:
trait Default {
fn default() -> Self;
}
下面就实现一下:
use std::default::Default;
#[derive(Debug)]
struct Any<T, U> {
t: T,
u: U,
}
impl<T, U> Default for Any<T, U>
where
T: Default,
U: Default,
{
fn default() -> Self {
Any {
t: T::default(),
u: U::default(),
}
}
}
fn main() {
println!("{:?}", Any::<i32, Vec<String>>::default()); // Any { t: 0, u: [] }
}