前往:将引用类型作为参数

Certain types in Go are reference types: maps, slices, channels, functions, and methods.

Sometimes you need to use pointers to references. For example,

type Stack []interface{}
func (stack *Stack) Push(x interface{}) { 
    *stack = append(*stack, x)
}

You need it because all arguments are passed by copying the value, and append() might need to reallocate memory in the slice's capacity is not big enough. I get that.

First question. How about map types? If I have a custom type based on a map, should I better always pass a pointer to it if some key:value insertions or deletions are expected?

Second question. What about other reference types? Channel, for example. I can imagine a situation where I build a custom type based on a channel to implement some custom pre-processing for the values being passed to a channel. Pointers needed here too?

Sorry if this is basic as heck, but I really want to get a good grasp of the subject.

查看全部
doudizhi947129
doudizhi947129
2015/07/01 19:47
  • reference
  • parameters
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复