doudizhi947129
2015-07-01 19:47前往:将引用类型作为参数
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.
- 点赞
- 回答
- 收藏
- 复制链接分享
2条回答
为你推荐
- 前往:将引用类型作为参数
- parameters
- reference
- 2个回答