Lesson Overview

Hello! Today, we're exploring a fundamental facet of Go: Composition. Composition is a design principle in Go that enables code reuse. Unlike languages that use inheritance, Go opts for Composition. This lesson aims to understand Composition and how it applies in Go.

Understanding Struct Buzzwords

Composition in Go allows for the construction of complex types using simpler ones. In Go's Composition, you frequently encounter terms like Embedding and Anonymous Fields. Embedding involves including one struct inside another, creating a parent-child relationship. Anonymous Fields are declared in a struct without a name, and their type becomes their name.

type Point struct {
  X, Y float64
}

type Circle struct {
  Point   // Embedding Point struct into Circle
  Radius float64
}

In the example above, Point is an anonymous field in the Circle.

Working with Composition in Go: Part 1

Now, let's see Composition in action in Go, using structs:

package main
import "fmt"

// 'Person' struct
type Person struct {
  Name   string
  Age    int
}

// 'Student' struct, embedding 'Person'
type Student struct {
  Person
  Grade   int
}

func main() {   
  john := Student{
    Person: Person{
      Name: "John Appleseed",
      Age:  21,
    },
    Grade: 12,
  }  
   
  fmt.Println(john.Name)  // Output: "John Appleseed"
}

Here, the Person struct is embedded into the Student struct. We then directly access the Name field from the Student struct instance named john.

Working with Composition in Go: Part 2

Note that we can also access the Name like this:

fmt.Println(john.Person.Name)

In some cases, this can be useful. For example, if the "child" struct has a field named the same as one of the fields of the "parent" struct, it would be a proper way to access it. Consider the following example:

type School struct {
  Name   string
}

type Student struct {
  Name   string
  School
}

In this case, a student has an embedded school. Both Student and School has fields Name, so here is how we distinct them:

student.Name //  accessing name of the student
student.School.Name //  accessing name of the student's school
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal