go语言结构体数组定义
介绍 (Introduction)
Building abstractions around concrete details is the greatest tool that a programming language can give to a developer. Structs allow Go developers to describe the world in which a Go program operates. Instead of reasoning about strings describing a Street
, City
, or a PostalCode
, structs allow us to instead talk about an Address
. They serve as a natural nexus for documentation in our efforts to tell future developers (ourselves included) what data is important to our Go programs and how future code should use that data appropriately. Structs can be defined and used in a few different ways. In this tutorial, we’ll take a look at each of these techniques.
围绕具体细节构建抽象是编程语言可以提供给开发人员的最大工具。 结构允许Go开发人员描述Go程序在其中运行的世界。 结构使我们无需再讨论描述Street
, City
或City
字符串, PostalCode
我们可以谈论Address
。 它们是文档的自然纽带,可以帮助我们告诉未来的开发人员(包括我们自己)哪些数据对我们的Go程序很重要,以及将来的代码应如何适当地使用这些数据。 可以以几种不同的方式定义和使用结构。 在本教程中,我们将研究每种技术。
定义结构 (Defining Structs)
Structs work like paper forms that you might use, for example, to file your taxes. Paper forms might have fields for textual pieces of information like your first and last names. Besides text fields, forms might have checkboxes to indicate Boolean values such as “married” or “single,” or date fields for birth date. Similarly, structs collect different pieces of data together and organize them under different field names. When you initialize a variable with a new struct, it’s as though you’ve photocopied a form and made it ready to fill out.
结构的工作方式类似于纸质表格,例如,您可以用来报税。 纸质表格可能包含文本信息字段,例如您的名字和姓氏。 除文本字段外,表单还可能具有复选框,以指示布尔值(例如“已婚”或“单身”)或生日字段的日期字段。 同样,结构将不同的数据收集在一起,并以不同的字段名称进行组织。 当您使用新的结构体初始化变量时,就好像您已经将表格影印并准备好填写一样。
To create a new struct, you must first give Go a blueprint that describes the fields the struct contains. This struct definition usually begins with the keyword type
followed by the name of the struct. After this, use the struct
keyword followed by a pair of braces {}
where you declare the fields the struct will contain. Once you have defined the struct, you are then able to decla