doulu4233 2016-12-24 02:11
浏览 47

Golang中的变量初始化和作用域

I am learning go lang and I came across below code

var kvstore = make(map[string][]byte)

// this function instantiates the database
func init_db() {
    kvstore = make(map[string][]byte)
}

// put inserts a new key value pair or updates the value for a
// given key in the store
func put(key string, value []byte) {
    kvstore[key] = value
}

// get fetches the value associated with the key
func get(key string) []byte {
    v, _ := kvstore[key]
    return v
}

I have 2 doubts:

  1. why is it required to initialize kvstore variable once globally and then once in init_db function?

  2. When someone calls put/get function from other module how is the state of kvstore maintained? (In 'C' we generally have to explicitly pass the data structure to the function but in this case put or get directly works on global kvstore variable)

  • 写回答

1条回答 默认 最新

  • dqqlziv195281 2016-12-24 02:25
    关注

    There is no need to initialize kvstore twice.

    You can think of the global kvstore variable as something similar to variable with static duration in C. And it's not safe to access map concurrently with writes. You might need to synchronize, just like accessing static global variable in C.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条