How to set value to empty interface{}

2,706 views
Skip to first unread message

Th3x0d3r

unread,
Apr 11, 2017, 9:22:41 AM4/11/17
to golang-nuts
Hey there !

How can i set the value of an interface{} parameter from other interface{} source

Playground : https://play.golang.org/p/utwO2Ru4Eq

Output expected:

Val 1: &{XML}
Val 2: &{XML}

Thanks

T L

unread,
Apr 11, 2017, 9:46:00 AM4/11/17
to golang-nuts


func GetClient(method string, resp interface{}) error {
    result := GetMessage("XML")
    resp = result
    fmt.Printf("Val 1: %v\n", resp)
    return nil
}

resp is an input parameter, when you pass a value as this parameter into the GetClient function,
it is copied into the call in fact.
Modifications on this copy will not be reflected to the original value outside of the called function.

If you do want to make the modifications visible to caller, you can return it as an output result, or use a pointer parameter instead.

 

pierre...@gmail.com

unread,
Apr 11, 2017, 9:52:20 AM4/11/17
to golang-nuts
Either pass around the pointer to your struct or use a dedicated interface to alter the struct contents.
Examples of each here and there.

Th3x0d3r

unread,
Apr 11, 2017, 10:10:25 AM4/11/17
to golang-nuts
AFAIK empty interfaces{} are passed by reference

Th3x0d3r

unread,
Apr 11, 2017, 10:11:20 AM4/11/17
to golang-nuts
I would but need to use empty interfaces{} as parameters

Th3x0d3r

unread,
Apr 11, 2017, 10:15:38 AM4/11/17
to golang-nuts
It works this way, but need to use the GetMessage interface value

James Bardin

unread,
Apr 11, 2017, 10:37:54 AM4/11/17
to golang-nuts


On Tuesday, April 11, 2017 at 10:10:25 AM UTC-4, Th3x0d3r wrote:
AFAIK empty interfaces{} are passed by reference


Nothing in go is "pass by reference". The interface value is always copied. 

pierre...@gmail.com

unread,
Apr 11, 2017, 10:41:18 AM4/11/17
to golang-nuts
In Go, everything is passed by value, including interfaces (empty or not).

So, you cannot change the value pointed to by an interface unless you "unbox" it: https://play.golang.org/p/uzccweBdzV

Further reading:
to understand interfaces inner workings: https://research.swtch.com/interfaces, even though I think that the interface value is now always a pointer.

Th3x0d3r

unread,
Apr 11, 2017, 12:04:30 PM4/11/17
to golang-nuts
Not as I expected, but it works,  Would it be possible not to use an specific type (*SomeMessage) an instead use interface{} type in assertion?

pierre...@gmail.com

unread,
Apr 11, 2017, 12:50:32 PM4/11/17
to golang-nuts
Go is a typed language.
I guess it is possible using reflect: https://play.golang.org/p/41gguwtlSC but I would steer away from it.
Reply all
Reply to author
Forward
0 new messages