英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论