因此,鉴于您对问题的描述确实相当模糊,我将首先说明我将如何“管理”地图。为简单起见,我将把所有逻辑封装在接收器函数中,因此将地图封装在自定义类型中:
type dataMap struct {
data map[int][]int
nmax int
}
func New(Nmax int) *dataMap {
return &dataMap{
data: make(map[int][]int, Nmax),
nmax: Nmax,
}
}
// Get - return slice for given key
func (d dataMap) Get(k int) []int {
s, ok := d.data[k]
if !ok {
return nil // optionally return error
}
return s
}
// Set - set/append values to a given key - this is not safe for concurrent use
// if that's needed, add a RWMutex to the type
func (d *dataMap) Set(k int, vals ...int) error {
s, ok := d.data[k]
if !ok {
s = make([]int, 0, d.nmax) // allocate slice of given length
}
// optionally check for nil-values + ensure we're not exceeding the nmax
checked := make([]int, 0, len(vals))
for i := range vals {
if vals[i] != 0 {
checked = append(checked, vals[i])
}
}
if len(s) + len(checked) > d.nmax {
return errors.New("max capacity exceeded")
}
s = append(s, checked...) // append values
d.data[k] = s // update map
return nil
}
这减少了不必要的内存(重新)分配调用。它还确保我可以在 O(1) 操作中获得地图中任何切片的长度,而不必担心 nil 值:
myData := New(10)
fmt.Println(myData.Set(4, 1, 2, 3, 4))
fmt.Println(len(myData.Get(4))) // 4
fmt.Println(cap(myData.Get(4))) // 10
// nil-values are filtered out
myData.Set(4, 5, 6, 7, 0, 0, 0, 0)
fmt.Println(len(myData.Get(4))) // 7
fmt.Println(cap(myData.Get(4))) // 10
// exceeding capacity of 10
fmt.Println(myData.Set(4, 8, 9, 10, 11)) // max capacity exceeded
您可以通过使用数组而不是切片来管理容量,但这确实需要您手动跟踪要开始附加值的索引/偏移量。一般来说,你不会在 golang 中使用数组,以免在非常非常特殊的情况下。在这种情况下,我只会选择带有固定上限的切片。这样做的好处是您可以拥有不同长度的切片。结果也很容易测试,因为像这样的类型很适合用接口类型替换它
type DataContainer interface {
Get(k int) []int
Set(k int, vals ...int) error
Declare(k, capacity int) error // error if k is already in use?
}