Home >Backend Development >Golang >How Can We Idiomatically Create Complex Hierarchies of Structs in Go?

How Can We Idiomatically Create Complex Hierarchies of Structs in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 02:26:22515browse

How Can We Idiomatically Create Complex Hierarchies of Structs in Go?

Creating Complex Hierarchies of Structs Idiomatically in Go

The concept of inheritance in object-oriented languages like C allows for the creation of complex type hierarchies. However, Go, a language that lacks classes and inheritance, poses a unique challenge when it comes to representing hierarchical structures.

The Empty Method Approach of the Go Compiler

In the Go compiler, a hierarchy of types is represented using interfaces with empty methods. While the Go FAQ suggests this approach to explicitly guarantee interface implementation, it can lead to an excessive number of empty methods.

Go's Embedding and Empty Methods

Go supports embedding both structs and interfaces. Empty methods are introduced to ensure that types explicitly implement interfaces, thereby preventing type assignment incompatibilities.

Struct Embedding to Reduce Empty Methods

An alternative approach is to create struct implementations that embed higher-level types. This allows for automatic inheritance of method sets, reducing the need for empty methods.

For instance, consider a hierarchy:

Object
--Immovable
----Building
----Mountain
--Movable
----Car
----Bike

The Object interface and implementation:

type Object interface {
  object()
}

type ObjectImpl struct {}

func (o *ObjectImpl) object() {}

The Immovable interface and implementation:

type Immovable interface {
  Object
  immovable()
}

type ImmovableImpl struct {
  ObjectImpl // Embedded
}

func (i *ImmovableImpl) immovable() {}

The Building struct:

type Building struct {
  ImmovableImpl // Embedded
}

By embedding the ImmovableImpl struct, Building automatically inherits the immovable() method without the need for an additional empty method. This technique minimizes the number of empty methods required, especially as the hierarchy grows or interfaces contain more than one method.

The above is the detailed content of How Can We Idiomatically Create Complex Hierarchies of Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn