Embedding Structs in Golang

GoGoBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This challenge aims to test your understanding of struct embedding in Golang. You will be required to create a struct that embeds another struct and access its fields and methods.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) go/ObjectOrientedProgrammingGroup -.-> go/struct_embedding("`Struct Embedding`") subgraph Lab Skills go/struct_embedding -.-> lab-15434{{"`Embedding Structs in Golang`"}} end

Struct Embedding

Create a struct named container that embeds a struct named base. The base struct should have a field named num of type int and a method named describe() that returns a string. The container struct should have a field named str of type string. The container struct should be able to access the num field and describe() method of the base struct.

Requirements

  • The base struct should have a field named num of type int.
  • The base struct should have a method named describe() that returns a string.
  • The container struct should have a field named str of type string.
  • The container struct should embed the base struct.
  • The container struct should be able to access the num field and describe() method of the base struct.

Example

$ go run struct-embedding.go
co={num: 1, str: some name}
also num: 1
describe: base with num=1
describer: base with num=1

Summary

In this challenge, you learned how to embed a struct in another struct and access its fields and methods. You also learned how to bestow interface implementations onto other structs using struct embedding.

Other Go Tutorials you may like