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:
why is it required to initialize kvstore
variable once globally and then once in init_db
function?
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)
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.