Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is indexing on the slice pointer not allowed in golang

Tags:

slice

pointers

go

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.

like image 947
srini Avatar asked Jul 19 '16 20:07

srini


People also ask

Which data types does not support indexing?

Set data structure does not support indexing.

Is a slice in Golang a pointer?

Go Pointers Slices are Pointers to Array Segments Slices are pointers to arrays, with the length of the segment, and its capacity. They behave as pointers, and assigning their value to another slice, will assign the memory address.


2 Answers

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).

like image 96
evanmcdonnal Avatar answered Sep 20 '22 04:09

evanmcdonnal


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
like image 28
peterSO Avatar answered Sep 21 '22 04:09

peterSO