dongzhuifeng1843 2018-03-08 14:56
浏览 16
已采纳

映射为方法接收者

Does anyone know why map can be used as a value receiver, but when working with slices only the pointer receiver has to be used? Why the map is changing after the method call?

Example for map:

package main

import (
    "fmt"
)

type hashMap map[string]int

func (s hashMap) Add(k string, v int) {
    s[k] = v
}

func main() {
    var s hashMap
    s = make(hashMap, 0)
    fmt.Println(s)
    s.Add("abc", 15)
    fmt.Println(s)
}

Output:

map[]
map[abc:15]

Example for slice:

package main

import (
    "fmt"
)

type slice []int

func (s *slice) Add(v int) {
    (*s) = append(*s, v)
}

func main() {
    var s slice
    s = make(slice, 0)
    fmt.Println(s)
    s.Add(15)
    fmt.Println(s)
}

Output:

[]
[15]
  • 写回答

2条回答 默认 最新

  • dongwo5589 2018-03-08 15:28
    关注

    A map variable, after make, is a pointer to the map header: *hmap. The map pointer is passed by value

    // A header for a Go map.
    type hmap struct {
        // Note: the format of the Hmap is encoded in ../../cmd/internal/gc/reflect.go and
        // ../reflect/type.go. Don't change this structure without also changing that code!
        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
    }
    

    A slice variable is a struct: slice. The slice struct is passed by value.

    type slice struct {
        array unsafe.Pointer
        len   int
        cap   int
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?
  • ¥15 metamask如何添加TRON自定义网络