英文:
why is indexing on the slice pointer not allowed in golang
问题
当我运行下面的代码时,我得到编译器错误,提示不支持索引。
txs := make([]string, 2)
txs[0] = "A"
p := &txs
fmt.Println(p[0])
我试图理解为什么不支持对切片指针进行索引。我可以将指针变量复制为值变量,然后进行索引,但我很好奇为什么语言不支持对切片指针进行索引;这样做会更方便。或者是否有一种我不知道的方法可以实现?请告诉我你的想法。
英文:
When I run the below code, I get the compiler error saying that indexing is not supported.
txs := make([]string, 2)
txs[0] = "A"
p := &txs
fmt.Println(p[0])
I'm trying to understand why indexing on the slice pointer is not supported. I can make a copy of the pointer variable to value variable and then do indexing, but I'm curious to understand why the language is not supporting the indexing on slice pointer; it'd be so much convenient to do so. or is there a way to do it that i'm not aware? please let me know your thoughts.
答案1
得分: 45
将指针 p
解引用后写为 (*p)
:
package main
import (
"fmt"
)
func main() {
txs := make([]string, 2)
txs[0] = "A"
p := &txs
fmt.Println((*p)[0])
}
Playground: https://play.golang.org/p/6Ex-3jtmw44
输出:
A
英文:
Write (*p)
to dereference the pointer p
:
package main
import (
"fmt"
)
func main() {
txs := make([]string, 2)
txs[0] = "A"
p := &txs
fmt.Println((*p)[0])
}
Playground: https://play.golang.org/p/6Ex-3jtmw44
Output:
A
答案2
得分: 3
在这里发生了一种抽象,语言设计者选择不将其应用于指针。从实际的角度来看,这可能是因为指针并不指向数组的开头(比如内存块)。如果你熟悉索引操作,通常会使用类似于startingAddress + index * sizeof(dataType)
的方式来进行。因此,当你有值类型时,它已经提供了一个抽象,隐藏了额外的间接层。我猜测语言的作者们认为,当你有一个指向切片对象的指针时,这样做是没有意义的,因为它指向的是实际的内存,这可能会产生误导。它已经引起了一些混淆,但对于很多开发者来说,他们可能永远不会意识到这种抽象实际上是存在的(就像在大多数情况下,在操作切片和数组时语法上几乎没有明显的区别)。
英文:
There's an abstraction happening there and the language designer chose not to apply it to the pointer. To give some practical reason, this is likely due to the fact that the pointer doesn't point to the beginning of an array (like the block of memory. If you're familiar with indexing this is generally done with something like startingAddress + index * sizeof(dataType)
). So when you have the value type, it's already providing an abstraction to hide the extra layer of indirection that occurs. I assume the language authors didn't think it made sense to do this when you have a pointer to the slice object, given that points off to the actual memory that would be a pretty misleading. It already causes some confusion as is, but for a lot of developers, they probably will never realize this abstraction exists at all (like in most cases there is no noticeable difference in syntax when operating on a slice vs and array).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论