doulangyu9636 2019-01-25 02:09
浏览 28
已采纳

函数返回变量的地址…最终是另一个变量吗?

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
", state)
   fmt.Printf("%v
", 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?

  • 写回答

1条回答 默认 最新

  • dtrb96410 2019-01-25 02:11
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭