包级收集

I have a globally defined map on a package level. When ever i refer to it, it seems has though the map is recreated on every usage.

1) Is that a correct assumption ?

2) What's the reasoning behind it ? (I'm guessing immutability and thread safety)

3) How would a globally used collection be defined in GO to be used by all packages (i.e. Think of a Global static definition in languages like C#) ?

The package :

package device

import "strconv"

var Devices =  map[int]Device { 1 :Device{ name : "Lamp" }, 
                    2: Device{ name : "AirConditioner"} }

type Device struct{
    name string
    Value int
    State int
}

func (d *Device) String() string  {
    return d.name + "," + strconv.Itoa(d.Value) + "," + strconv.Itoa(d.State)
}

Usage :

import d "hello/app/device"

func main() {  

    device := d.Devices[1]
    device.State = 1

    // device after change ->  Lamp,0,1
    fmt.Println("Device After Change -> " + device.String())

    deviceAgain := d.Devices[1]
    // using the device again prints default values -> Lamp,0,0
    fmt.Printf(deviceAgain.String())
 }

First you have to declare your global variable using pointer variables

var Devices =  map[int]*Device {
    1 :{ name : "Lamp" },
    2: { name : "AirConditioner" },
}

To make it safe for concurrent reads and writes, one way is to declare a new struct and add a lock

type Devices struct {
    sync.Mutex
    data map[int]*Device
}

func (d *Devices) Get(i int) *Device {
    d.Lock()
    defer d.Unlock()
    return d.data[i]
}

func (d *Devices) SetState(i int, s int) {
    d.Lock()
    defer d.Unlock()
    d.data[i].State = s
}