How to initiate a go struct with a nested struct whose name has package name

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

How to initiate a go struct with a nested struct whose name has package name

问题

我有一个定义如下的Go结构体:

type Record struct {
	events.APIGatewayProxyRequest          `json:",omitempty"`
	events.APIGatewayWebsocketProxyRequest `json:",omitempty"` //nolint:all
	events.SQSEvent                        `json:",omitempty"`
}

我想知道如何初始化这个结构体。我尝试了:

Record{events.APIGatewayProxyRequest: {}}

但是它给我一个错误:invalid field name events.APIGatewayProxyRequest in struct literal。似乎在结构体中不能使用包名作为键名。正确的初始化方式是什么?

英文:

I have a go struct defined as below:

type Record struct {
	events.APIGatewayProxyRequest          `json:",omitempty"`
	events.APIGatewayWebsocketProxyRequest `json:",omitempty"` //nolint:all
	events.SQSEvent                        `json:",omitempty"`
}

I wonder how I can initiate this struct. I tried:

Record{events.APIGatewayProxyRequest: {}}

but it gives me an error: invalid field name events.APIGatewayProxyRequest in struct literal. It seems the name including package name can't be used as key name in the struct. What is the right way to initiate it?

答案1

得分: 1

当你将一个类型嵌入到一个结构体中时,包含结构体的字段名与嵌入类型的类型名相同,但不包含包选择器。所以:

event := Record{
  APIGatewayProxyRequest: events.APIGatewayProxyRequest{ ... },
}

初始化的右侧是该类型的字面量,因此你需要使用完整的类型名(包括选择器)。

英文:

When you embed a type into a struct, the enclosing struct has a field name that is the same as the type name of the embedded type without the package selector. So:

event:=Record{
  APIGatewayProxyRequest: events.APIGatewayProxyRequest{ ... },
}

The right hand side of the initialization is a literal of that type, so you use the full type name (with the selector).

huangapple
  • 本文由 发表于 2023年2月13日 08:07:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75430964.html
匿名

发表评论

匿名网友

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

确定