Documentation
¶
Overview ¶
A handful of examples using the standard builtin types.
Example (StructsBasic) ¶
ExampleStructs illustrates creating a simple struct.
package main import ( "fmt" ) func main() { type contact struct { firstName string lastName string } friends := []contact{ { firstName: "John", lastName: "Smith", }, { "Jane", "Doe", }, } for i, v := range friends { fmt.Printf("%02d: %s, %s\n", i, v.lastName, v.firstName) } }
Output: 00: Smith, John 01: Doe, Jane
Example (StructsComposedFields) ¶
package main import ( "fmt" ) func main() { type contact struct { firstName string lastName string } type friend struct { contact circle string } friends := []friend{ { contact: contact{ firstName: "John", lastName: "Smith", }, circle: "school", }, { contact{ "Jane", "Doe", }, "work", }, } for i, v := range friends { fmt.Printf("%02d: %6s %s, %s\n", i, v.circle, v.lastName, v.firstName) } }
Output: 00: school Smith, John 01: work Doe, Jane
Example (StructsComposedMethods) ¶
package main import "fmt" type contact struct { firstName string lastName string } type friend struct { contact circle string } func (c contact) fullName() string { return c.firstName + " " + c.lastName } func (f friend) summary() string { return fmt.Sprintf("%s %s", f.circle, f.fullName()) } func main() { friends := []friend{ { contact: contact{ firstName: "John", lastName: "Smith", }, circle: "school", }, { contact{ "Jane", "Doe", }, "work", }, } for i, f := range friends { fmt.Printf("%02d:\n", i) fmt.Printf(" %s\n", f.summary()) fmt.Printf(" %s %s\n", f.circle, f.fullName()) fmt.Printf(" %s %s %s\n", f.circle, f.firstName, f.lastName) } }
Output: 00: school John Smith school John Smith school John Smith 01: work Jane Doe work Jane Doe work Jane Doe
Click to show internal directories.
Click to hide internal directories.