Home  >  Article  >  Backend Development  >  How to start a go structure with a nested structure whose name has the package name

How to start a go structure with a nested structure whose name has the package name

PHPz
PHPzforward
2024-02-06 09:45:16818browse

如何使用名称具有包名称的嵌套结构来启动 go 结构

Question content

I have a go structure defined as follows:

type record struct {
    events.apigatewayproxyrequest          `json:",omitempty"`
    events.apigatewaywebsocketproxyrequest `json:",omitempty"` //nolint:all
    events.sqsevent                        `json:",omitempty"`
}

I want to know how to start this structure. I have tried before:

Record{events.APIGatewayProxyRequest: {}}

But it gives me an error: invalid field name events.apigatewayproxyrequest in struct literal . It seems that names containing package names cannot be used as key names in structures. What's the correct way to start it?


Correct answer


When embedding a type into a structure, the field names of the enclosing structure are the same as the type names of the embedded type (without the package selector). so:

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

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

The above is the detailed content of How to start a go structure with a nested structure whose name has the package name. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete