Ad space (banner)
๐ŸนGo Lessons
Lesson 9 / 68

Structs (an Object-Oriented Style)

In this lesson you will learn an object-oriented style using Go structs, and understand how to keep data and behaviour together. This is for anyone searching for "Go structs how to use".

Go has no classes. Instead you combine a struct with functions (methods) bound to it to achieve something similar. Picture defining "the data for an animal" and "the behaviour of an animal making a sound" separately, then tying them together.

The sample code gives the Animal struct the fields Name and Sound, and builds a message in the method func (a Animal) Speak() string. The (a Animal) part is called the receiver and states which struct the method is bound to.

A common stumbling block for beginners is how to write that receiver. Without understanding the difference between a value receiver and a pointer receiver, it is easy to change the struct inside a method and find the change was never reflected.

In real-world development, being able to design in an object-oriented way through this simple mechanism, without classes, is regarded as one of the defining features of Go.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)