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

huangapple go评论72阅读模式
英文:

How to get a new variable of the same type of another variable with Golang

问题

你好!以下是翻译好的内容:

我该如何做到这一点?我想要一个函数,返回一个与其参数类型相同的变量。我需要类似下面的代码:

type Whatever struct {
    Title string
}

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

// 这样是不起作用的
BB := new(thetype)

希望对你有帮助!如果还有其他问题,请随时提问。

英文:

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

得分: 4

如果你想从reflect.Type创建一个新的值,可以使用reflect.New函数:

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

这将返回一个reflect.Value类型的值。你可以使用.Interface()方法和类型断言来恢复到原始类型。

在Go Playground上有一个示例:https://play.golang.org/p/rL-Hm0IUpd

英文:

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

huangapple
  • 本文由 发表于 2016年11月6日 21:09:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/40449695.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定