Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the second pair of braces in this Golang struct?

Tags:

syntax

struct

go

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

This looks like a struct with an embedded field sync.Mutex but I can't get my head around the second set of braces. It compiles and executes but what's up? Why does the label on the make instruction matter (it does) and the comma? Thanks...

like image 401
kayak Avatar asked Nov 01 '16 23:11

kayak


1 Answers

The example you have is equivalent to:

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

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

Except in your example you do not declare a type of Cache and instead have an anonymous struct. In your example, as oppose to my Cache type, the type is the entire

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

So think of the second pair of braces as the

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

part.

make is a built in function that works similarly to C's calloc() which both initialize a data structure filled with 0'd values, in Go's case, certain data structures need to be initialized this way, other's (for the most part structs) are initialized with 0'd values automatically. The field there is needed so that the compiler now's cache.mapping is a empty map[string]string.

The comma there is part of Go's formatting, you can do Cache{mapping: make(map[string]string)} all on one line, but the moment the field's assignment is on a different line than the opening and closing braces, it requires a comma.

like image 173
Christian Grabowski Avatar answered Oct 19 '22 15:10

Christian Grabowski