What are the differences between the multiple ways to create zero-sized structs?

前端 未结 2 990
离开以前
离开以前 2021-02-19 02:58

I found four different ways to create a struct with no data:

  • struct A{} // empty struct / empty braced struct
    
  • <         
    
    
            
2条回答
  •  感情败类
    2021-02-19 03:25

    struct D; // unit struct
    

    This is the usual way for people to write a zero-sized struct.

    struct A{} // empty struct / empty braced struct
    struct B(); // empty tuple struct
    

    These are just special cases of basic struct and tuple struct which happen to have no parameters. RFC 1506 explains the rational to allow those (they didn't used to):

    Permit tuple structs and tuple variants with 0 fields. This restriction is artificial and can be lifted trivially. Macro writers dealing with tuple structs/variants will be happy to get rid of this one special case.

    As such, they could easily be generated by macros, but people will rarely write those on their own.

    struct C(()); // unit-valued tuple struct
    

    This is another special case of tuple struct. In Rust, () is a type just like any other type, so struct C(()); isn't much different from struct E(u32);. While the type itself isn't very useful, forbidding it would make yet another special case that would need to be handled in macros or generics (struct F(T) can of course be instantiated as F<()>).

    Note that there are many other ways to have empty types in Rust. Eg. it is possible to have a function return Result<(), !> to indicate that it doesn't produce a value, and cannot fail. While you might think that returning () in that case would be better, you might have to do that if you implement a trait that dictates you to return Result but lets you choose T = () and E = !.

提交回复
热议问题