Go in Practice, Second Edition cover
welcome to this free extract from
an online version of the Manning book.
to read more
or

3 Structs, interfaces, and generics

 

This chapter covers

  • Using structs to represent data and methods
  • Comparing Go’s structs and interfaces with object-oriented and functional programming patterns
  • Creating interfaces to extend functionality of custom types
  • Making code more flexible and reusable by implementing generic types

As we move toward more complex features and approaches in Go, including concurrency, let’s first dig into some of the core building blocks of the language. We’ll start by going into a little more depth on the nonprimitive data structure in Go. Custom structures, or structs, are the cornerstone of how we represent bespoke data and relationships between data. Go provides a system for building, extending, and manipulating data structs. In this chapter, we’ll explore how structs, interfaces, and methods work together to empower you to design intuitive data structures and their methods and use them for data isolation/control and state management.

3.1 Using structs to represent data

In chapters 1 and 2, we built some basic command-line applications and a web server, using the custom data structures. In Go, structs are powerful language tools that represent rich data structures beyond primitives; you can use them to define the behaviors and data flow of your applications. Used thoughtfully, they keep your code readable and free of cruft and code duplication; they also accommodate encoding data with tags.

3.1.1 Creating custom data structures

3.1.2 Functions inside structs

3.1.3 Anonymous identifiers

3.1.4 Tags in structs

3.1.5 Encoding data in JSON format

3.2 Contrasts with functional and object-oriented programming

3.3 Extending functionality with interfaces

3.4 Simplifying code with generics

3.4.1 Using functions with generics

3.4.2 Using constraints and type approximations

Summary