AndreKR
AndreKR

Reputation: 33678

How to not initialize part of a struct

I want to combine what I think is called a grouped global with an embedded lock like this:

var stats struct {
    sync.RWMutex
    m map[string]statsEntry
}

Unfortunately for the map to be useful, it has to be made, so the code becomes:

var stats = struct {
  sync.RWMutex
  m map[string]statsEntry
}
{
  ???,
  make(map[string]statsEntry),
}

What to put instead of ????

Upvotes: 2

Views: 84

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109388

You use a type literal:

stats := struct {
    sync.RWMutex
    m map[string]statsEntry
}{
    sync.RWMutex{},
    make(map[string]statsEntry),
}

But since the zero value of sync.RWMutex is valid, you can skip it and specify the fields you're assigning

stats := struct {
    sync.RWMutex
    m map[string]statsEntry
}{
    m: make(map[string]statsEntry),
}

But it's often just clearer to define the type locally

type s struct {
    sync.RWMutex
    m map[string]statsEntry
}

stats = s{m: make(map[string]statsEntry)}

Upvotes: 6

Related Questions