2 回答

TA貢獻1909條經驗 獲得超7個贊
您正在創建一個全局變量存儲,而您很可能希望將其封裝在您的 Routes 結構中:
package main
type Routes struct{
store map[string][]byte
}
func NewRoutes() *Routes {
return &Routes{
store: make(map[string][]byte),
}
}
func (c *Routes) SetRoutes(key string, routes []byte) error {
c.store[key] = routes
return nil
}
func main() {
routes := NewRoutes()
routes.SetRoutes("key", []byte("routes"))
}
請參閱:https ://go.dev/play/p/3M4kAfya6KE 。這確保地圖的范圍限定為您的 Routes 結構并且僅初始化一次。

TA貢獻1826條經驗 獲得超6個贊
您可以檢查它是否存在nil以及make是否存在:
func (c *Routes) SetRoutes(key string, routes []byte) error {
if store == nil {
store = make(map[string][]byte)
}
store[key] = routes
return nil
}
或者,只需在mainfunc 中進行:
func main() {
store = make(map[string][]byte)
routes := NewRoutes()
routes.SetRoutes("key", []byte("routes"))
}
- 2 回答
- 0 關注
- 114 瀏覽
添加回答
舉報