2

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 ????

1 Answer 1

6

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)}
Sign up to request clarification or add additional context in comments.

1 Comment

I always struggle finding type names for global variables because I read you shouldn't name them var something somethingType.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.