创建默认结构的最惯用的方法 [英] Most idiomatic way to create a default struct
问题描述
要创建一个默认结构体,我曾经看到fn new() ->Rust 中的 Self
,但今天,我发现了 Default
.所以有两种方法可以创建默认结构体:
struct Point {x: i32,y:i32,}impl 点 {fn new() ->自己 {观点 {x: 0,y: 0,}}}impl 默认点 {fn default() ->自己 {观点 {x: 0,y: 0,}}}fn 主(){让 _p1 = Point::new();让 _p2: Point = Default::default();}
什么是更好/最惯用的方法?
如果您不得不选择一个,那么实现 Default
trait 是更好的选择以允许您的类型在更多地方通用,而 new
方法可能是试图直接使用您的代码的人会寻找的.p>
但是,您的问题是错误的二分法:您可以两者,我鼓励您这样做!当然,重复自己很愚蠢,所以我会从另一个调用一个(哪个方式并不重要):
impl 点 {fn new() ->自己 {默认::默认()}}
我在具有成员数据结构的结构中使用 Default::default()
,我可能会在其中更改实现.例如,我可能当前正在使用 HashMap
但想切换到 BTreeMap
.使用 Default::default
让我少了一个改变的地方.
在这种特殊情况下,您甚至可以导出Default
,使其非常简洁:
#[派生(默认)]结构点{x: i32,y:i32,}impl 点 {fn new() ->自己 {默认::默认()}}fn 主(){让 _p1 = Point::new();让 _p2: Point = Default::default();}
To create a default struct, I used to see fn new() -> Self
in Rust, but today, I discovered Default
. So there are two ways to create a default struct:
struct Point {
x: i32,
y: i32,
}
impl Point {
fn new() -> Self {
Point {
x: 0,
y: 0,
}
}
}
impl Default for Point {
fn default() -> Self {
Point {
x: 0,
y: 0,
}
}
}
fn main() {
let _p1 = Point::new();
let _p2: Point = Default::default();
}
What is the better / the most idiomatic way to do so?
If you had to pick one, implementing the Default
trait is the better choice to allow your type to be used generically in more places while the new
method is probably what a human trying to use your code directly would look for.
However, your question is a false dichotomy: you can do both, and I encourage you to do so! Of course, repeating yourself is silly, so I'd call one from the other (it doesn't really matter which way):
impl Point {
fn new() -> Self {
Default::default()
}
}
Clippy even has a lint for this exact case!
I use Default::default()
in structs that have member data structures where I might change out the implementation. For example, I might be currently using a HashMap
but want to switch to a BTreeMap
. Using Default::default
gives me one less place to change.
In this particular case, you can even derive Default
, making it very succinct:
#[derive(Default)]
struct Point {
x: i32,
y: i32,
}
impl Point {
fn new() -> Self {
Default::default()
}
}
fn main() {
let _p1 = Point::new();
let _p2: Point = Default::default();
}
这篇关于创建默认结构的最惯用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!