Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 147 ยท Structs and Methods

Object-Oriented Programming in Go

Map classes, objects, encapsulation, inheritance and polymorphism onto Go - structs with methods, exported fields, embedding instead of inheritance, and interfaces for polymorphism.

If you come from Java, C#, Python or C++, you may wonder where Go keeps its classes. It does not have any. There is no class keyword, no extends, no constructors in the language and no private modifier. And yet Go programs are full of objects with state and behavior, hidden details and interchangeable implementations. Go simply reaches the same goals with fewer, more general tools: structs, methods, embedding and interfaces.

This lesson walks through the four classic pillars of object-oriented programming (encapsulation, abstraction, inheritance and polymorphism) and shows the Go version of each one. It is a map for people who already know OOP; if the pieces are new, read structs, methods and interfaces first.

A class becomes a struct plus methods

In a class-based language, data and behavior live inside one class block. In Go they are declared separately but belong together by the receiver: a method is a function with one extra parameter that names the type it belongs to.

Go A struct with methods is Go's class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output is hits=2 and then =1. Three details are worth noticing. A constructor is only a convention: a plain function, usually called NewSomething, that returns a ready value (see constructors and options). There is no this or self; you name the receiver yourself, and short names such as c are the style. And a method with a pointer receiver (*Counter) may change the value, while a value receiver (Counter) works on a copy; value vs pointer receivers explains when to pick which. Go also encourages types whose zero value is useful, so that var zero Counter works without any setup.

Encapsulation: exported or not

Languages with classes use private, protected and public. Go has exactly one rule, and it is about the first letter of a name:

  • A name that starts with an uppercase letter is exported: visible to every package that imports yours.
  • A name that starts with a lowercase letter is unexported: visible only inside its own package.

The unit of hiding is therefore the package, not the type. Two types in the same package can read each other's lowercase fields, which is usually what you want because code in one package is written and reviewed together. To protect an invariant, put the type in its own package, keep the fields lowercase and offer exported methods. The code below keeps a package-style boundary visible by naming the "outside" view explicitly:

Go Protecting an invariant with unexported fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You see <nil> 100, then insufficient funds, then deposit must be positive, got -5, and finally Mira 100. Go style has two small conventions here: a getter is named after the field without Get (Balance, not GetBalance), and a setter, when you need one, is called SetBalance. Many Go types skip getters and setters completely and just export the field; hide a field only when you have an invariant to protect.

Abstraction with interfaces

In Java you write class Dog implements Animal and the compiler checks the promise at the class. In Go an interface is satisfied implicitly: if a type has the methods, it implements the interface, and nobody has to declare it. This is called structural typing.

Go
type Speaker interface {
	Speak() string
}

Any type with a Speak() string method is a Speaker, even one written years before the interface existed, and even one from another package. That lets the consumer define the small interface it needs, rather than the producer predicting every use. Interface design builds on this idea.

Polymorphism

Polymorphism is the ability to treat different types through one common view. In Go this is exactly what a variable of interface type does: the method call is dispatched to the dynamic type at run time.

Go Polymorphism through an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The three shapes print circle 3.14, rect 6.00, circle 0.79, and the total is 9.93. totalArea knows nothing about circles or rectangles; adding a Triangle with the two methods needs no change to it. That is the open/closed principle, without any inheritance tree.

Inheritance becomes composition and embedding

Go has no inheritance. The language designers chose composition over inheritance: build a bigger type out of smaller ones. When you embed a type by listing it without a field name, its fields and methods are promoted to the outer type:

Go Embedding promotes fields and methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output is Rex, Rex has 4 legs, Woof and .... It looks like inheritance, but there are two important differences. First, a Dog is not an Animal: you cannot pass a Dog where an Animal value is required. You must pass d.Animal, or use an interface that both satisfy. Second, there is no virtual dispatch to the outer type: when Animal.Describe calls a.Sound(), it calls Animal's version, never Dog's. In Java an overridden method would be chosen. If you need that behavior, pass the behavior in explicitly, as an interface field or a function. Embedding covers these rules in depth, including embedded interfaces and name conflicts.

Embedding a type is a way to reuse code, not a way to create a type hierarchy. If you find yourself wanting three levels of embedded structs, step back and look for an interface and a few small functions instead.

Cheat sheet: OOP term to Go feature

OOP idea Go equivalent
Class struct type plus methods with receivers
Object / instance A value of the struct type (often a pointer to it)
Constructor A NewX function; zero values should also work
this / self The receiver, named by you
public / private Exported (Uppercase) / unexported (lowercase), per package
Interface interface type, satisfied implicitly
Inheritance Embedding (composition with promotion)
Method overriding Defining a method with the same name on the outer type
Abstract class An interface, plus a struct that holds shared code
Static method A package-level function
Destructor None; use defer and Close methods

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a Go type declare that it implements an interface?

    Go interfaces are satisfied implicitly. Any type whose method set contains the interface's methods implements it.
  2. 2. What decides whether a struct field is visible to other packages?

    An uppercase first letter exports the name. Lowercase names are visible only inside their own package.
  3. 3. A Dog embeds Animal. Which statement is true?

    Promotion lets you write d.Describe(), but the types stay distinct and there is no virtual dispatch back to the outer type.
  4. 4. Which is the idiomatic name for the getter of an unexported field balance?

    Go style drops the Get prefix: the exported method is named after the field.

Summary

  • Go has no classes: a struct plus methods plays that role, and a NewX function plays the constructor.
  • Encapsulation works at package level with exported (Uppercase) and unexported (lowercase) names.
  • Interfaces are implicit; small interfaces defined by the consumer give you abstraction and polymorphism.
  • Embedding gives code reuse through promotion, but it is composition, not inheritance: there is no subtype relation and no virtual dispatch.
  • Prefer composition, small interfaces and useful zero values over deep hierarchies.

Next: Interfaces goes deeper into the feature that gives Go its abstraction and polymorphism.