Structs e interfaces

Go Struct Embedding and Composition

Go has no inheritance. Reuse fields and methods by embedding one struct in another.

  • Intermediário
  • 4 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • Embedding a struct
  • Promoted fields and methods
  • Composition
type Dog struct
  • Dog
    • AnimalName, Describe()
    • Breed

Build types from smaller types

Go has no inheritance. Instead, a struct can embed another struct, and the fields and methods of the embedded type become available on the outer one. This is called composition.

Dog embeds Animal, so dog.Name and dog.Describe() work as if they were declared on Dog. The embedded value can still be reached by its type name, as in dog.Animal.Name. Service gets a Log method by embedding Logger.

Pontos-chave

  1. Dog embeds Animal and gets Name and Describe.
  2. The embedded value is still reachable: dog.Animal.
  3. Embedding is composition, not inheritance.

Exemplo executável de Go

Go
Executar código →
main.go
package main

import "fmt"

type Animal struct {
	Name string
}

func (a Animal) Describe() string {
	return a.Name + " is an animal"
}

type Dog struct {
	Animal // embedded: Dog gets Name and Describe
	Breed  string
}

func (d Dog) Speak() string {
	return d.Name + " says woof"
}

type Logger struct{ Prefix string }

func (l Logger) Log(message string) { fmt.Println(l.Prefix + message) }

type Service struct {
	Logger
	Name string
}

func main() {
	dog := Dog{Animal: Animal{Name: "Rex"}, Breed: "Collie"}
	fmt.Println(dog.Describe())
	fmt.Println(dog.Speak())
	fmt.Println(dog.Animal.Name, dog.Breed)

	service := Service{Logger: Logger{Prefix: "[api] "}, Name: "users"}
	service.Log("started " + service.Name)
}
Gerar um botão Run para este exemplo Resultado da execução
Rex is an animal
Rex says woof
Rex Collie
[api] started users

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Próxima: Temperature Converter →

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios