Dima
Dima

Reputation: 40500

A function returns an address of a variable ... ends up being a different variable?

This code:

package main

import (
    "fmt"
    "encoding/json"
)


type State struct { Foo string }
type Handler struct { state State }

func (handler Handler) State() *State { return &handler.state }

func main() {
   input := `{"Foo": "bar"}`
   handler := Handler{}
   state := handler.State()
   json.Unmarshal([]byte(input), state)


   fmt.Printf("%v\n", state)
   fmt.Printf("%v\n", handler.state)
}

Prints

&{bar}
{}

(see for yourself)

This buffles me: handle.State() returns the address of handler.state, so how is it possible that state (which is &handler.state) and handler.state end up containing different things (one is empty, the other is not)?

If I change state := handler.State() to state := &handler.state, then it works the way I expect it to.

What am I missing here?

Upvotes: 0

Views: 45

Answers (1)

Thundercat
Thundercat

Reputation: 120941

The method is taking the address of a field in the receiver argument handler. A new handler value is created on every invocation of the function.

Use a pointer receiver to get the results you expect:

func (handler *Handler) State() *State { return &handler.state }

In this case, the function returns the address of the field in the caller's handler.

Upvotes: 9

Related Questions