Essential Go  Edit on GitHub      File Issue


A struct groups related variables into a single entity.

Additionally, structs can have methods, similar to classes in C++ or Java.

Unlike classes in C++ or Java, structs don’t implement inheritance. You can achieve some of the code re-use with struct embedding.

Zero value of struct is a struct whose fields are set to their respective zero values.

Basics of structs:

// Person describes a person
type Person struct {
	FirstName string
	LastName  string

// FullName returns full name of a person
func (p *Person) FullName() string {
	return fmt.Sprintf("%s %s", p.FirstName, p.LastName)

func main() {
	// zero value of struct
	var p Person
	fmt.Printf("p: %v\n\n", p)

	p = Person{
		FirstName: "John",
		LastName:  "Doe",
	fmt.Printf("p: %v\n\n", p)

	// call a method on a struct
	fmt.Printf("p.FullName(): %s\n", p.FullName())
p: { }

p: {John Doe}

p.FullName(): John Doe
  ↑ ↓ to navigate     ↵ to select     Esc to close