问题描述
Go中的某些类型是引用类型:映射,切片,通道,函数和方法.
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)
}
之所以需要它,是因为所有参数都是通过复制值来传递的,并且 append()
可能需要在分片的容量不够大的情况下重新分配内存.我明白了.
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.
第一个问题. map
类型如何?如果我有一个基于 map
的自定义类型,那么如果需要某些key:value插入或删除操作,我是否应该最好始终传递一个指向它的指针?
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?
第二个问题.其他参考类型呢?例如 Channel
.我可以想象这样一种情况,我将基于通道构建自定义类型,以对传递到通道的值实施一些自定义预处理.这里也需要指针吗?
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.
推荐答案
当您将所有内容都视为一个值(其中某些值内部包含指针)时,规则相当简单.
The rules are fairly easy when you think of everything as a value, where some values contain pointers internally.
- 切片:当您需要修改长度或容量以更改切片的值时,请使用指针.
- 地图:请勿使用指针,因为地图值不会随着修改而改变.
- 函数和方法:不要使用指针,通过函数值具有相同的效果.
- chan :请勿使用指针.
- slices: Use a pointer when you may need to modify the length or capacity, which changes the value of the slice.
- maps: Don't use a pointer, since the map value doesn't change with modifications.
- functions and methods: Don't use a pointer, the same effect is had through function values.
- chan: Don't use a pointer.
当然也有例外,例如,如果您希望能够完全交换出地图,则需要使用指针来进行交换,但这是极少数情况.
There are of course exceptions, like if you want to be able to swap out a map entirely you would need to use pointer to do so, but these are rare cases.
这篇关于前往:将引用类型作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!