Set the interface value passed to the function in go

后端 未结 1 1788
猫巷女王i
猫巷女王i 2021-01-29 15:39

I want to change

Get(title string )(out interface{})

to something like :

Get(title string,out interface{})

So

1条回答
  •  野的像风
    2021-01-29 16:15

    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")
        }
    }
    

    0 讨论(0)
提交回复
热议问题