Jonathan
Jonathan

Reputation: 11375

Method on unnamed struct type

I'm trying to understand what the below code block does;

var cache = struct {
sync.Mutex
mapping map[string]string
} {
mapping: make(map[string]string),
}

I don't understand the presence of } { or what the last line does.

Upvotes: 0

Views: 65

Answers (2)

Adrian
Adrian

Reputation: 46572

Let's break it down:

// create a variable cache of type anonymous struct
var cache = struct {
    // Define anonymous struct fields
    sync.Mutex
    mapping map[string]string
} { // Close struct definition; open value literal
    mapping: make(map[string]string), // specify a field in the value
} // Close value literal

Basically this statement defines a variable cache, specifies its type, and assigns it a value. The first set of braces encloses the type definition, the second set encloses the value literal. The variable's type is struct { sync.Mutex, mapping map[string]string }.

Upvotes: 2

Thundercat
Thundercat

Reputation: 121129

The text

struct {
   sync.Mutex
   mapping map[string]string
} {
   mapping: make(map[string]string),
}

is a composite literal. The literal's type is the anonymous struct type:

struct {
   sync.Mutex
   mapping map[string]string
}

The literal's value is

{
   mapping: make(map[string]string),
}

Upvotes: 3

Related Questions