为什么在Go语言中,`*int`和`[]int`是不同的?

huangapple go评论93阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年9月8日 07:56:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/69095605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定