Her*_*ord 0 struct return return-type go
假设我有一个结构,例如:
type Tmp struct {
Number int
Text string
}
Run Code Online (Sandbox Code Playgroud)
是否有可能有一个返回匿名结构的方法?就像是:
func (t Tmp) MyStruct() struct {
return struct {
myVal string
}{
"this is my val"
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了上面的代码,但出现错误。这可以通过其他方式实现吗?
是的,这是可能的,但是您的函数签名在语法上不正确。struct是一个关键字,而不是一个类型。
它是这样有效的:
func (t Tmp) MyStruct() struct {
myVal string
} {
return struct {
myVal string
}{
"this is my val",
}
}
Run Code Online (Sandbox Code Playgroud)
测试它:
var t Tmp
fmt.Printf("%+v", t.MyStruct())
Run Code Online (Sandbox Code Playgroud)
输出将是(在Go Playground上尝试):
{myVal:this is my val}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这不是很方便,因为在返回值时必须在复合文字中重复结构定义。为了避免这种情况,您可以使用命名结果:
func (t Tmp) MyStruct() (result struct {
myVal string
}) {
result.myVal = "this is my val"
return
}
Run Code Online (Sandbox Code Playgroud)
这输出相同。在Go Playground上试试这个。
但最简单的是定义一个你想要返回的类型,一切都会很简单:
type MS struct {
myVal string
}
func (t Tmp) MyStruct() MS {
return MS{myVal: "this is my val"}
}
Run Code Online (Sandbox Code Playgroud)
在Go Playground上试试这个。