英文:
Why is *int different from []int in go
问题
在开始学习Go之前,我曾经使用C和C++进行一段时间的工作,我很好奇为什么在Go语言中*int
和[]int
被视为不同的类型。无论你是否认为它是一个数组,它们都应该是指向内存中某个位置的指针,指示int类型列表的开头。这个列表可能只有一个元素,但我的观点是,为什么在Go语言中[]int
和*int
不是同一种类型呢?
英文:
I worked with C
and C++
for a while before starting to learn go, and I'm curious why *int
and []int
are treated as different types in golang. Whether you want to think of it as an array or not is up to you, but they should both be pointers to some location in memory indicating the beginning of a list of type int. That list may very well be of size one, but my point is, why are []int
and *int
not the same thing in go?
答案1
得分: 7
一个[]int
在内部有三个值:指向支持数组的指针,支持数组的长度和支持数组的容量。Go运行时确保应用程序不会超出支持数组的边界。
一个*int
就像C语言中的指针一样。因为Go语言没有指针算术(除了unsafe包之外),所以不能像在C语言中那样使用*int
作为数组。
英文:
An []int
has three values internally: pointer to backing array, length of backing array and capacity of backing array. The Go runtime ensures that the application does index outside the bounds of the backing array.
An *int
is just a pointer as in C. Because Go does not have pointer arithmetic (outside of the unsafe package), a *int
cannot be used like an array as in C.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论