Reputation: 165
Do empty structures inside Box::new()
need curly braces? If not, is there a preferred style?
struct Empty;
// are these equivalent?
fn get_empty_box() -> Box<Empty> {
Box::new(Empty)
}
fn get_empty_box_alt() -> Box<Empty> {
Box::new(Empty {})
}
Upvotes: 2
Views: 147
Reputation: 71350
Depends on how they are defined.
If they are defined as struct Foo {}
then yes.
If they are defined as struct Foo();
then they need parentheses or braces, but it's uncommon to see them with braces.
If they're defined as struct Foo;
then they don't need braces (although they can accept them) and usually instantiated without braces.
The technical reason for that is that struct Foo;
defines, in addition to the struct itself, a constant with the same name that contains an instance of the struct. That is, const Foo: Foo = Foo {};
. When you spell Foo
without braces you just copy this constant.
In a similar fashion, tuple structs (struct Foo();
) define, in addition to the struct itself, a function that instantiates it: fn Foo() -> Foo { Foo {} }
.
Upvotes: 7