duanpu1111
2016-11-06 13:09 阅读 110
已采纳

如何使用Golang获取与另一个变量相同类型的新变量

How can I do this? I want a function to return a variable with the same type as one of its arguments. I need something like the below:

type Whatever struct {
    Title string
}

hey:= Whatever{Title:"YAY"}
thetype := reflect.ValueOf(hey).Kind()

// This does not work
BB:= new(thetype)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanqiao0153 duanqiao0153 2016-11-06 13:41

    If you want to create a new value from a reflect.Type you can do it with reflect.New:

    thetype := reflect.TypeOf(hey)
    BB:= reflect.New(thetype)
    

    This returns a reflect.Value
    You can then for example use .Interface() and type assertions to get back to the original type.

    Example on Go playground: https://play.golang.org/p/rL-Hm0IUpd

    点赞 评论 复制链接分享

相关推荐