构造器

描述

Rust没有构造器作为语言构造。 相反,惯例是使用一个关联函数new来创建一个对象:

#![allow(unused)] fn main() { /// Time in seconds. /// /// # Example /// /// ``` /// let s = Second::new(42); /// assert_eq!(42, s.value()); /// ``` pub struct Second { value: u64 } impl Second { // Constructs a new instance of [`Second`]. // Note this is an associated function - no self. pub fn new(value: u64) -> Self { Self { value } } /// Returns the value in seconds. pub fn value(&self) -> u64 { self.value } } }

默认构造器

Rust通过Defaulttrait支持默认构造器:

#![allow(unused)] fn main() { /// Time in seconds. /// /// # Example /// /// ``` /// let s = Second::default(); /// assert_eq!(0, s.value()); /// ``` pub struct Second { value: u64 } impl Second { /// Returns the value in seconds. pub fn value(&self) -> u64 { self.value } } impl Default for Second { fn default() -> Self { Self { value: 0 } } } }

如果所有类型的所有字段都实现了Default,也可以派生出Default,就像对Second那样:

#![allow(unused)] fn main() { /// Time in seconds. /// /// # Example /// /// ``` /// let s = Second::default(); /// assert_eq!(0, s.value()); /// ``` #[derive(Default)] pub struct Second { value: u64 } impl Second { /// Returns the value in seconds. pub fn value(&self) -> u64 { self.value } } }

**注意:**当为一个类型实现Default时,既不需要也不建议同时提供一个没有参数的相关函数new

**提示:**实现或派生Default的好处是,你的类型现在可以用于需要实现Default的地方,最突出的是标准库中的任何*or_default函数

参见

Latest commit fa8e722 on 22 Nov 2021