Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - How do you change the value of a pointer parameter?

Tags:

reflection

go

In Golang, is it possible to change a pointer parameter's value to something else?

For example,

func main() {
    i := 1
    test(&i)
}

func test(ptr interface{}) {
    v := reflect.ValueOf(ptr)

    fmt.Println(v.CanSet()) // false
    v.SetInt(2) // panic
}

https://play.golang.org/p/3OwGYrb-W-

Is it possible to have test() change i to point to another value 2?

like image 652
Some Noob Student Avatar asked May 12 '17 23:05

Some Noob Student


2 Answers

Not sure if this is what you were looking for, but yes you can change a pointer's value to something else. The code below will print 2 and 3:

package main

import (
    "fmt"
)

func main() {
    i := 1

    testAsAny(&i)
    fmt.Println(i)

    testAsInt(&i)
    fmt.Println(i)
}

func testAsAny(ptr interface{}) {
    *ptr.(*int) = 2
}

func testAsInt(i *int) {
    *i = 3
}
like image 84
janos Avatar answered Nov 01 '22 22:11

janos


Here's now to set the value using the reflect package. The key point is to set the pointer's element, not the pointer itself.

func test(ptr interface{}) {
  v := reflect.ValueOf(ptr).Elem()
  v.SetInt(2)
}

playground example

Note that the reflect package is not needed for this specific example as shown in another answer.

like image 27
Bayta Darell Avatar answered Nov 01 '22 23:11

Bayta Darell