duanhuang1699 2019-08-16 13:17
浏览 3
已采纳

包级收集

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())
 }
  • 写回答

1条回答 默认 最新

  • dphphvs496524 2019-08-16 17:40
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)