'Set reference in Go

How to pass an interface by reference and let the method fill it for me? Something like this:

var i CustomInterface
Get("title" , ref i)
i.SomeOperationWithoutTypeAssertion() //i is nil here(my problem)

func Get(title string, iRef ref interface{}){
     iRef = new(ATypeWhichImplementsTheUnderlyingInterface)
}

I want i not to be nil after calling the Get method. How to pass i as reference to the Get method?



Solution 1:[1]

Go doesn't have the concept of transparent reference arguments as found in languages like C++, so what you are asking is not possible: Your Get function receives a copy of the interface variable, so won't be updating variable in the calling scope.

If you do want a function to be able to update something passed as an argument, then it must be passed as a pointer (i.e. called as Get("title", &i)). There is no syntax to specify that an argument should be a pointer to an arbitrary type, but all pointers can be stored in an interface{} so that type can be used for the argument. You can then use a type assertion / switch or the reflect package to determine what sort of type you've been given. You'll need to rely on a runtime error or panic to catch bad types for the argument.

For example:

func Get(title string, out interface{}) {
    ...
    switch p := out.(type) {
    case *int:
        *p = 42
    case *string:
        *p = "Hello world"
    ...
    default:
        panic("Unexpected type")
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1