繁体   English   中英

为什么切片值有时会过时但不能映射值?

[英]why slice values can sometimes go stale but never map values?

我发现切片图功能和通道经常一起作为参考类型提及。 但是我注意到,切片的东西不会表现出任何参考行为,因为它们可能会过时:

   var s []int
   //must update slice value
   s = append(s, ...) 

要么

   //must use pointer if we want to expose the change
   func foo(s *[]int) error  
   //or change the function signature to return it like _append_
   func foo(s []int) (r slice, err error)

通常,我会牢记切片描述符实现的内部组件来理解这一点:切片值可以视为len,cap和data指针的结构。

但是地图值永远不需要像

   m := make(map[string]int)
   ...
   // don't know how to express with insertion, but you know what i mean.
   m = delete(m, "well")  

为什么? 映射值仅仅是指向映射描述符的指针吗? 如果是这样,为什么还不这样做呢?

在Go中,没有像C ++中那样的引用类型。 在Go中,一切都是通过价值传递的。 当在Go中使用术语“引用类型”时,它表示引用它们应表示的数据(通过指针)的类型。

切片是小型的,类似于结构的数据结构,由类型reflect.SliceHeader表示:

type SliceHeader struct {
        Data uintptr
        Len  int
        Cap  int
}

它包含一个指向基础数组中的切片的第一个元素的指针( SliceHeader.Data字段)。 该结构很小,可以有效地作为值传递,而无需传递其地址(并取消引用以间接访问其任何字段)。 切片的元素不存储在切片头中,而是存储在头的存储区域之外的数组中。 这意味着修改“指向”元素将修改原始切片的元素。

当您将(大于0)个元素附加到切片时,标头中的Len字段必须更改,因此用于描述包含附加元素的切片的新切片必须不同于追加之前的切片,这就是为什么您需要分配内置的append()函数的返回值。 (其他值也可能会更改,但是Len必须更改。)

映射被实现为指向runtime.hmap结构的指针:

type hmap struct {
    // Note: the format of the hmap is also encoded in cmd/compile/internal/gc/reflect.go.
    // Make sure this stays in sync with the compiler's definition.
    count     int // # live cells == size of map.  Must be first (used by len() builtin)
    flags     uint8
    B         uint8  // log_2 of # of buckets (can hold up to loadFactor * 2^B items)
    noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details
    hash0     uint32 // hash seed

    buckets    unsafe.Pointer // array of 2^B Buckets. may be nil if count==0.
    oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing
    nevacuate  uintptr        // progress counter for evacuation (buckets less than this have been evacuated)

    extra *mapextra // optional fields
}

如您所见,这是一个比切片标头复杂得多的数据结构,并且要大得多,将其作为值传递将是无效的。

从映射中添加/删除元素(键-值对)存储在此struct的字段所引用的存储桶中,但是由于映射在幕后被当作指针处理​​,因此您无需分配此类操作的结果。

为了完整hchan ,通道也被实现为指针,指向runtime包的hchan类型:

type hchan struct {
    qcount   uint           // total data in the queue
    dataqsiz uint           // size of the circular queue
    buf      unsafe.Pointer // points to an array of dataqsiz elements
    elemsize uint16
    closed   uint32
    elemtype *_type // element type
    sendx    uint   // send index
    recvx    uint   // receive index
    recvq    waitq  // list of recv waiters
    sendq    waitq  // list of send waiters

    // lock protects all fields in hchan, as well as several
    // fields in sudogs blocked on this channel.
    //
    // Do not change another G's status while holding this lock
    // (in particular, do not ready a G), as this can deadlock
    // with stack shrinking.
    lock mutex
}

这又是一个“胖”结构,其处理方式类似于地图值。

查看相关问题:

参数中使用的slice vs map

使用值接收器附加到具有足够容量的切片

golang切片是否按值传递?

Go中的“值语义”和“指针语义”是什么意思?

Slice是连续内存块上的薄纸包装,通常有益于部分或全部重用该内容(避免复制数据)。 地图没有这些特征。 这是一个具有复杂行为的复杂数据结构,您无法重复使用其存储(就像对切片一样)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM