Skip to Content
Learning Go, 2nd Edition
book

Learning Go, 2nd Edition

by Jon Bodner
January 2024
Beginner
494 pages
12h 30m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning Go, 2nd Edition

Chapter 7. Types, Methods, and Interfaces

As you saw in earlier chapters, Go is a statically typed language with both built-in types and user-defined types. Like most modern languages, Go allows you to attach methods to types. It also has type abstraction, allowing you to write code that invokes methods without explicitly specifying the implementation.

However, Go’s approach to methods, interfaces, and types is very different from that of most other languages in common use today. Go is designed to encourage the best practices advocated by software engineers, avoiding inheritance while encouraging composition. In this chapter, you’ll take a look at types, methods, and interfaces, and see how to use them to build testable and maintainable programs.

Types in Go

Back in “Structs”, you saw how to define a struct type:

type Person struct {
    FirstName string
    LastName  string
    Age       int
}

This should be read as declaring a user-defined type with the name Person to have the underlying type of the struct literal that follows. In addition to struct literals, you can use any primitive type or compound type literal to define a concrete type. Here are a few examples:

type Score int
type Converter func(string)Score
type TeamScores map[string]Score

Go allows you to declare a type at any block level, from the package block down. However, you can access the type only from within its scope. The only exceptions are types exported from other packages. I’ll talk more about those in Chapter 10.

Note ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Designing Data-Intensive Applications, 2nd Edition

Designing Data-Intensive Applications, 2nd Edition

Martin Kleppmann, Chris Riccomini

Publisher Resources

ISBN: 9781098139285Errata PageSupplemental Content