Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do struct declarations sometimes contain blank fields?

Tags:

go

From the golang spec

// A struct with 6 fields.
struct {
    x, y int
    u float32
    _ float32  // padding
    A *[]int
    F func()
}
  • Are there any practical scenarios of using the blank _ fields inside a struct? (some code snippets would be appreciated)
like image 560
Salah Eddine Taouririt Avatar asked Dec 02 '13 17:12

Salah Eddine Taouririt


People also ask

Can structs have an empty definition?

An empty struct is a struct type without fields struct{} . The cool thing about an empty structure is that it occupies zero bytes of storage.

Can you have an empty struct?

An empty structIt occupies zero bytes of storage. As the empty struct consumes zero bytes, it follows that it needs no padding. Thus a struct comprised of empty structs also consumes no storage.

How do you know if a struct field is empty?

Checking for an empty struct in Go is straightforward in most cases. All you need to do is compare the struct to its zero value composite literal. This method works for structs where all fields are comparable.

Can you have an empty struct in C?

Yes, it is allowed in C programming language that we can declare a structure without any member and in that case the size of the structure with no members will be 0 (Zero). It will be a Zero size structure.


1 Answers

The padding is exactly what it is called: Some padding to align the following field to your needs, e.g. to match the layout of a C struct. It cannot be accessed (at least not without package unsafe).

like image 174
Volker Avatar answered Sep 21 '22 05:09

Volker