Go Series Tutorial--16. Structural body

Source: Internet
Author: User
Tags comparable uppercase letter
This is a creation in Article, where the information may have evolved or changed. Welcome to the 16th Tutorial [Golang Series Tutorial] (/SUBJECT/2). # # # What is a struct? A struct is a user-defined type that represents a collection of several fields (field). Sometimes it is time to integrate the data together, rather than make the data non-linked. In this case, you can use the struct body. For example, an employee has a ' firstName ', ' lastName ', and ' age ' three attributes, and it is reasonable to combine these attributes in a struct ' employee '. # # # struct declaration ' ' Gotype employee struct {firstName string lastName string Age int} ' ' in the code snippet above, declares a struct type ' Employee ', which has ' firs Tname ', ' lastName ' and ' age ' three fields. By declaring the same type of field on the same line, the struct can become more compact. In the structure above, ' firstName ' and ' lastName ' belong to the same ' string ' type, so the struct can be rewritten as: ' ' Gotype Employee struct {firstName, lastName string AG E, the struct ' Employee ' above the salary int} ' is called * * named struct (Named Structure) * *. We created a new type called ' Employee ', which can be used to create struct variables of type ' employee '.   Declaring a struct can also be done without declaring a new type, a struct type called an anonymous struct (Anonymous Structure) * *. "' Govar employee struct {firstName, lastName string Age int} ' '" ' Creates a * * anonymous struct * * ' employee '. # # # Create a named struct by the following code, we define a * * named struct ' Employee ' * *. ' Gopackage mainimport ("FMT") type Employee struct {firstName, lastName string age, Salary Int}func main () {//creating Structure using FIELD names EMP1: = employee{firstName: "Sam", age:25, salary:500, LastName: "Anderson",}//creating structure without us ing field names EMP2: = employee{"Thomas", "Paul", "$" fmt. Println ("Employee 1", EMP1) fmt. Println ("Employee 2", EMP2)} ' [Online Run Program] (Https://play.golang.org/p/uhPAHeUwvK) in line 7th of the above program, we created a named struct ' Employee '. In line 15th, by specifying the value of each field name, we define the struct variable ' emp1 '. The order of field names is not necessarily the same as the order in which the struct types are declared. Here we change the position of ' lastName ' and move it to the end. There will be no problem with this. In line 23rd of the above program, we omit the field name when we define ' EMP2 '. In this case, you need to ensure that the order of the field names is the same as the order in which the struct is declared. The program will output: ' Employee 1 {Sam Anderson 500}employee 2 {Thomas Paul 29 800} ' # # # Create anonymous struct ' ' Gopackage mainimport ("FMT") fun C Main () {Emp3: = struct {firstName, lastName string age, Salary int} {firstName: "Andreah", LastName: "Nikola", Age:3 1, salary:5000,} fmt. Println ("Employee 3", Emp3)} ' [Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/TEMFM3OZIQ) in line 3rd of the above program, we define a * * Anonymous struct variable * * ' Emp3 '. As we have mentioned above, this struct is called anonymous because it simply creates a new struct variable ' em3 ' without defining any struct type. The program will output: ' Employee 3 {andreah Nikola 31 5000} ' ## # 0 Value of the struct (zero value) when the defined struct is not explicitly initialized, the field of the struct is assigned the default of zero. ' Gopackage mainimport ("FMT") type Employee struct {firstName, lastName string age, Salary Int}func main () {var emp4 E Mployee//zero valued Structure FMT. Println ("Employee 4", Emp4)} "[Running Program Online] (Https://play.golang.org/p/p7_OpVdFXJ) The program defines ' Emp4 ', but does not initialize any values. So ' firstName ' and ' lastName ' are assigned a value of string 0 (' "'). The ' age ' and ' salary ' are assigned a value of 0 (0) for Int. The program outputs: ' Employee 4 {0 0} ' Of course you can also specify the initial values for some fields and ignore the other fields. This way, the ignored field names are assigned a value of zero.   ' Gopackage mainimport ("FMT") type Employee struct {firstName, lastName string age, Salary Int}func main () {EMP5 : = employee{firstName: "John", LastName: "Paul",} fmt. Println ("Employee 5", EMP5)} ' [Online Run Program] (https://play.golang.org/p/w2gPoCnlZ1) in the above program in line 14th and 15th, we initialized the ' firstName ' and ' LastName ', while ' age ' and ' salary ' are not initialized. So ' age ' and ' salary ' are assigned zero values. The program will output: ' Employee 5 {John Paul 0 0} ' # # # access to the struct's field dot operator '. ' The field used to access the struct body. ' Gopackage mainimport ("FMT") type Employee struct {firstName, lastName string age, Salary INt}func Main () {emp6: = employee{"Sam", "Anderson", "6000}" FMT. Println ("First Name:", Emp6.firstname) fmt. Println ("Last Name:", Emp6.lastname) fmt. Println ("Age:", Emp6.age) fmt. Printf ("Salary: $%d", Emp6.salary)} "[Running Program Online] (Https://play.golang.org/p/GPd_sT85IS) **emp6.firstname** in the above program Accessed the field ' firstName ' of the struct ' emp6 '. The program outputs: ' First Name:sam last Name:anderson age:55 Salary: $6000 ' can also create a ' struct ' of 0 values and assign values to each field later. ' Gopackage mainimport ("FMT") type Employee struct {firstName, lastName string age, Salary Int}func main () {var emp7 E Mployee emp7.firstname = "Jack" emp7.lastname = "Adams" FMT. Println ("Employee 7:", EMP7)} ' [Online Run Program] (Https://play.golang.org/p/ZEOx10g7nN) in the above program, we define ' EMP7 ', then give ' FirstName ' and ' LastName ' assignment. The program outputs: ' Employee 7: {Jack Adams 0 0} ' the pointer to the struct can also create a pointer to the struct body. ' Gopackage mainimport ("FMT") type Employee struct {firstName, lastName string age, Salary Int}func main () {emp8: = &A mp employee{"Sam", "Anderson", 6000} fmt. Println ("First Name:", (*EMP8). FiRstname) fmt. Println ("Age:", (*EMP8))} "[Running Program Online] (Https://play.golang.org/p/xj87UCnBtH) in the above program, **emp8** is a pointer to the struct ' Employee ' The pointer. ' (*EMP8). FirstName ' means to access the ' firstName ' field of the struct ' emp8 '. The program outputs: ' First name:samage:55 ' **go language allows us to use ' emp8.firstname ' instead of an explicit dereference ' (*EMP8) when accessing the ' firstName ' field. FirstName ' * *. ' Gopackage mainimport ("FMT") type Employee struct {firstName, lastName string age, Salary Int}func main () {emp8: = &A mp employee{"Sam", "Anderson", 6000} fmt. Println ("First Name:", Emp8.firstname) fmt. Println ("Age:", Emp8.age)} ' [Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/0ZE265QQ1H) in the above program, we use ' emp8.firstname ' to access ' FirstName ' field, the program will output: ' First name:samage:55 ' # # # Anonymous field when we create a struct, the field can have only type, and No field name. Such fields are called Anonymous fields (Anonymous field). The following code creates a ' person ' struct that contains two anonymous fields ' string ' and ' int '. ' Gotype person struct {string int} ' We will then use the anonymous field to write a program. "' Gopackage mainimport (" FMT ") type person struct {string Int}func main () {p: = person{" Naveen ", + FMT. Println (P)} "[Running Program online] (Https://play.golang. org/p/yf-dgdvsrc) in the above program, the struct ' person ' has two anonymous fields. ' P: = person{' Naveen ', 50} ' defines a variable of type ' person '. The program outputs ' {Naveen 50} '. * * Although the anonymous field does not have a name, the name of the anonymous field defaults to its type * *. For example, in the ' person ' structure above, although the fields are anonymous, Go defaults to these field names as their respective types. So the ' person ' struct has two fields named ' String ' and ' int '. ' Gopackage mainimport ("FMT") type person struct {string Int}func main () {var P1 person p1.string = "Naveen" P1.int = FMT. Println (p1)} "[Running Program Online] (Https://play.golang.org/p/K-fGNxVyiA) in line 14th and 15th of the above program, we have visited the anonymous field of the ' person ' struct, We use the field type as the field name, "string" and "int", respectively. The output of the above program is as follows: "' {Naveen 50} ' # # # # # of nested struct (Nested Structs) The field of the struct may also be a struct. Such structures are called nested structures. ' Gopackage mainimport ("FMT") type address struct {city, state string}type person struct {name string age int Address Address}func Main () {var p person p.name = ' Naveen ' p.age = p.address = Address {city: ' Chicago ', State: ' Illinois ', } FMT. Println ("Name:", P.name) fmt. Println ("Age:", P.age) fmt. Println ("City:", p.address.city) fmt. Println ("state:", P.address.state)} "[Run Program Online] (Https://play.GOLANG.ORG/P/46JKQFDTPO) The above structure ' person ' has a field ' address ', and ' address ' is also a struct. The program output: ' ' Name:naveen age:50 city:chicago State:illinois ' # # # Ascending field (promoted fields) if there is an anonymous struct type field in the struct, the field in the anonymous struct is called To raise the field. This is because the ascending field is like an external struct, and can be accessed directly from the external struct body. I know this definition is complicated, so let's just study the code to understand it. ' Gotype address struct {City, state string}type person struct {name string age int Address} ' ' in the code snippet above, the ' person ' struct has a An anonymous field ' address ', and ' address ' is a struct. Now that the struct ' Address ' has ' city ' and ' state ' two fields, accessing the two fields is just like declaring it directly in ' person ', so we call it the ascending field. ' Gopackage mainimport ("FMT") type address struct {city, state string}type person struct {name string age int Address} Func main () {var p person p.name = ' Naveen ' p.age = p.address = address{City: ' Chicago ', State: ' Illinois ',} fmt. Println ("Name:", P.name) fmt. Println ("Age:", P.age) fmt. Println ("City:", p.city)//city is promoted field FMT. Println ("state:", P.state)//state is promoted field} "[Online Run Program] (https://play.golang.org/p/OgeHCJYoEy) in the above code in line 26th and 27 lines, we used the syntax ' p.city ' and ' P.STate ', access the ascending Fields ' city ' and ' state ' as if they were declared in the struct ' P '. The program outputs: ' ' Name:naveen age:50 city:chicago State:illinois ' ' # # # export struct and field if the struct name starts with an uppercase letter, it is an export type that other packages can access (exported Type). Similarly, if the first letter of a field in a struct is capitalized, it can also be accessed by other packages. Let's use a custom package and write a program to better understand it. In the ' src ' directory of your Go workspace, create a folder named ' Structs '. Also create a directory ' computer ' in ' structs '. In the ' computer ' directory, save the following program in a file named ' Spec.go '. "' Gopackage computertype Spec struct {//exported struct Maker string//exported field model string//unexported field Pr Ice int//exported Field} "" In the code snippet above, created a ' computer ' package, which has an export struct type ' Spec '. ' Spec ' has two export fields ' Maker ' and ' price ', and a non-exported field ' model '. Next we will import this package in the main package and use the ' Spec ' struct. "' Gopackage mainimport" structs/computer "import" FMT "Func Main () {var spec computer. Spec Spec. Maker = "Apple" spec. Price = 50000 FMT. PRINTLN ("Spec:", spec)} ' package structure is as follows: ' ' src structs computer spec.go main.go ' in line 3rd of the above program, we import the ' computer ' package. In lines 8th and 9th, we visited the two export fields ' Maker ' and ' price ' of the struct ' Spec '. Execute the command ' Go install structs ' and ' workspacepath/bin/structs ', run the program. Such asIf we try to access the non-exported field ' model ', the compiler will error. Replace the contents of ' Main.go ' with the following code. "' Gopackage mainimport" structs/computer "import" FMT "Func Main () {var spec computer. Spec Spec. Maker = "Apple" spec. Price = 50000 Spec.model = "Mac Mini" FMT. PRINTLN ("Spec:", Spec)} "in line 10th of the above program, we tried to access the non-exported field ' model '. If you run this program, the compiler generates an error: **spec.model undefined (cannot refer to unexported field or method model) * *. # # # struct Equality (Structs equality) * * struct is a value type. If each of its fields is comparable, the struct is also comparable. If the corresponding fields of the two struct variables are equal, the two variables are also equal * *. "' Gopackage mainimport (" FMT ") type name struct {firstName string lastName string}func main () {name1: = name{" Steve "," Jobs "} name2: = name{" Steve "," Jobs "} if name1 = = name2 {fmt. Println ("name1 and name2 are equal")} else {fmt. Println ("name1 and name2 is not Equal")} Name3: = Name{firstname: "Steve", LastName: "Jobs"} name4: = name{} Name4.firstna me = "Steve" if Name3 = = name4 {fmt. Println ("Name3 and Name4 are equal")} else {fmt. Println ("Name3 and name4 is not Equal")}} "[Run Program Online] (https://play.golang.org/p/AU1FkdsPk7In the preceding code, the struct type ' name ' contains two ' string ' types. Because strings are comparable, you can compare two struct variables of type ' name '. The above code is equal to ' name1 ' and ' name2 ', while ' name3 ' and ' name4 ' are not equal. The program outputs: "' name1 and name2 is equal name3 and name4 is not equal ' * * struct variables cannot be compared if the struct contains non-comparable fields. * * ' Gopackage mainimport ("FMT") type image struct {data map[int]int}func main () {image1: = image{data:map[int]int{0 : 155,}} image2: = image{data:map[int]int{0:155,}} if Image1 = = image2 {fmt. Println ("Image1 and Image2 are equal")}} "[Running Program Online] (HTTPS://PLAY.GOLANG.ORG/P/T4SVXOTYSG) in the code above, the struct type ' image ' contains a ' Map ' type of field. Because the ' map ' type is not comparable, ' image1 ' and ' image2 ' are not comparable. If you run the program, the compiler will error: * * ' main.go:18:invalid operation:image1 = = Image2 (struct containing map[int]int cannot be compared) ' * *. [GitHub] (https://github.com/golangbot/structs) has the source code for this tutorial. * * Previous tutorial-[pointers] (https://studygolang.com/articles/12262) * * * Next Tutorial-[method] (https://studygolang.com/articles/12264) * *

via:https://golangbot.com/structs/

Author: Nick Coghlan Translator: Noluye proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

3,038 Reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.