设计思路
- 处理空 map 情况:在
packageA
中提供初始化CustomType
的方法,确保InnerData
在使用前被正确初始化,避免空指针异常。
- 并发访问处理:使用
sync.RWMutex
来保护InnerData
,读操作使用读锁,写操作使用写锁,以保证数据一致性和安全性。
- 跨包使用的可维护性和扩展性:将对
CustomType
的操作封装成方法,在packageA
中提供统一的接口,这样在packageB
使用时只需要调用这些接口,而不需要直接操作InnerData
,提高可维护性和扩展性。
关键代码片段
packageA
package packageA
import (
"sync"
)
type CustomType struct {
InnerData map[string]interface{}
mu sync.RWMutex
}
// NewCustomType 创建一个新的 CustomType 实例,并初始化 InnerData
func NewCustomType() *CustomType {
return &CustomType{
InnerData: make(map[string]interface{}),
}
}
// Get 获取 InnerData 中的值
func (ct *CustomType) Get(key string) (interface{}, bool) {
ct.mu.RLock()
defer ct.mu.RUnlock()
value, exists := ct.InnerData[key]
return value, exists
}
// Set 设置 InnerData 中的值
func (ct *CustomType) Set(key string, value interface{}) {
ct.mu.Lock()
defer ct.mu.Unlock()
if ct.InnerData == nil {
ct.InnerData = make(map[string]interface{})
}
ct.InnerData[key] = value
}
packageB
package packageB
import (
"fmt"
"your_project_path/packageA"
)
func UseCustomType() {
custom := packageA.NewCustomType()
custom.Set("key1", "value1")
value, exists := custom.Get("key1")
if exists {
fmt.Printf("Value for key1: %v\n", value)
}
}