Skip to Content
Learning Go
book

Learning Go

by Jon Bodner
March 2021
Beginner
375 pages
8h 59m
English
O'Reilly Media, Inc.
Content preview from Learning Go

Chapter 7. Types, Methods, and Interfaces

As we 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 most other languages in common use today. Go is designed to encourage the best practices that are advocated by software engineers, avoiding inheritance while encouraging composition. In this chapter, we’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” we 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 only access the type from within its scope. The only exceptions are exported package block level types. We’ll talk more about those in Chapter 9.

Note

To ...

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

Learning Go, 2nd Edition

Learning Go, 2nd Edition

Jon Bodner

Publisher Resources

ISBN: 9781492077206Errata PageSupplemental Content