1
package main

import "fmt"

func doStuff(q interface{}) {
    *q = MyStruct{2}
}

type MyStruct struct {
    f1 int
}

func main() {
    ms := MyStruct{1}
    doStuff(&ms)
    fmt.Printf("Hello, playground: %v\n", ms)
}

Is it possible to set ms through pointer q to have new value MyStruct{2}? I am getting this error invalid indirect of q (type interface {})

2
  • 1
    It's possible but you need to use a type assertion or reflection. The type interface{} is not a pointer type, so you cannot use pointer indirection on it. Commented Mar 30, 2021 at 6:16
  • 1
    Your question seems to imply that you think of interface{} as "any type". This is wrong. interface{} is not "any type" it is the empty interface, literally interface{} and a distinct fixed type like uint16, chan bool, []string or io.Reader. It is worth redoing the Tour of Go once more to become familiar with Go's types system. Commented Mar 30, 2021 at 7:19

2 Answers 2

2

interface{} is not a pointer type. So, you cannot change it's underlying value. Instead, you can modify q value and return it from the doStuff function if you really need to do so.

example:

package main

import "fmt"

func doStuff(q interface{}) interface{} {
    q = &MyStruct{2}
    return q
}

type MyStruct struct {
    f1 int
}

func main() {
    var ms interface{} = MyStruct{1}
    ms = doStuff(&ms)
    fmt.Printf("Hello, playground: %v\n", ms)
}

Sign up to request clarification or add additional context in comments.

Comments

1

You can't using the interface{} type, since it's not a literal type you can memory address like you're attempting. An interface type describes general behavior, not a specific value.

If you use the MyStruct type directly, you can get a pointer and do what you want.

package main

import "fmt"

func doStuff(q *MyStruct) {
    *q = MyStruct{2}
}

type MyStruct struct {
    f1 int
}

func main() {
    ms := MyStruct{1}
    doStuff(&ms)
    fmt.Printf("Hello, playground: %v\n", ms)
}

Go playground linke

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.