英文:
What values have pointer semantics?
问题
在Go语言中,一切都是按值传递的。调用一个带有值的函数会导致该值被复制,并且函数只能访问该值的副本。
指针语义允许通过值传递的方式更新“原始”值,就像我们传递指向它的指针一样。
哪些类型具有指针语义?
英文:
In Go, everything is pass by value. Calling a function with a value results in the value being copied and function only accessing the copy of the value.
Pointer semantics allow something passed "by value" a way in which to update the "original" value, just as if we would have passed a pointer to it.
What types have pointer semantics?
答案1
得分: 2
所有类型的变量都需要使用指针来修改传递给函数的值。
唯一的例外是某些引用类型的成员可以在不传递指针的情况下进行修改,但是类型值不能在不使用指针的情况下进行修改。
修改切片成员的示例(但不修改切片本身)(playground):
func main() {
s := []int{1, 2, 3, 4}
modifySliceMember(s)
fmt.Println(s) // [90 2 3 4]
}
func modifySliceMember(s []int) {
if len(s) > 0 {
s[0] = 99
}
}
修改切片本身的示例(playground):
func main() {
s := []int{1, 2, 3, 4}
modifySlice(&s)
fmt.Println(s) // []
}
func modifySlice(s *[]int) {
*s = make([]int, 0)
}
然而,需要注意的是,即使在这种情况下,严格来说我们并没有真正改变传递的值。在这种情况下,传递的值是一个指针,并且该指针是不能被改变的。
英文:
Variables of all types require the use of a pointer, if you wish to modify the value passed to a function.
The only exception is that some reference types may have their members modified without passing a pointer, but the type value cannot be modified without using a pointer.
Example of modifying a slice member (but not the slice itself) (playground):
func main() {
s := []int{1, 2, 3, 4}
modifySliceMember(s)
fmt.Println(s) // [90 2 3 4]
}
func modifySliceMember(s []int) {
if len(s) > 0 {
s[0] = 99
}
}
To modify the slice itself (playground):
func main() {
s := []int{1, 2, 3, 4}
modifySlice(&s)
fmt.Println(s) // []
}
func modifySlice(s *[]int) {
*s = make([]int, 0)
}
However, note that even in this case, we're not really changing the passed value strictly speaking. The passed value in this case is a pointer, and that pointer cannot be changed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论