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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。