0

In C, we can move pointer like so:

int main()
{
    int array[4] = { 1, 2, 3, 4};
    int *q;
    q = array; 
    printf("%d\n", q[0]); /* 1 */
    q += 3; 
    printf("%d\n", q[0]); /* 4 */
}

Is there a way to do something like this in Golang?

Odinovsky
  • 551
  • 1
  • 6
  • 23
  • See https://golang.org/ref/spec#Slice_types - it's not at all the same, but now that the question is already closed, there's no way to add a proper description of using slices to get the effect you want. – torek Dec 08 '19 at 08:29
  • @torek I have tried to do it in my answer. – PumpkinSeed Dec 08 '19 at 08:30
  • @PumpkinSeed: what the OP might want is: `q := arr[:]` followed by `q = q[3:]`. See also https://stackoverflow.com/q/29110426/1256452 – torek Dec 08 '19 at 08:31

3 Answers3

3

Golang does not support pointer arithmetic since that is a source of vulnerabilities.

References: https://tour.golang.org/moretypes/1

pr-pal
  • 3,248
  • 26
  • 18
1

Golang does not support pointer arithmetic in order to increase the safety during development.

alessiosavi
  • 2,753
  • 2
  • 19
  • 38
1

For example, using Go slices,

package main

import "fmt"

func main() {
    array := [4]int{1, 2, 3, 4}
    slice := array[:]
    fmt.Printf("%d\n", slice[0]) /* 1 */
    slice = slice[3:]
    fmt.Printf("%d\n", slice[0]) /* 4 */
}

Playground: https://play.golang.org/p/82pXFkHLSfd

Output:

1
4
peterSO
  • 158,998
  • 31
  • 281
  • 276