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 8. Generics

“Don’t repeat yourself” is common software engineering advice. It’s better to reuse a data structure or a function than it is to re-create it, because it’s hard to keep code changes in sync between duplicated code. In a strongly typed language like Go, the type of every function parameter and every struct field must be known at compile time. This strictness enables the compiler to help validate that your code is correct, but sometimes when you’ll want to reuse the logic in a function or the fields in a struct with different types. Go provides this functionality via type parameters, which are colloquially referred to as generics. In this chapter you’ll learn why people want generics, what Go’s implementation of generics can do, what generics can’t do, and how to use them properly.

Generics Reduce Repetitive Code and Increase Type Safety

Go is a statically typed language, which means that the types of variables and parameters are checked when the code is compiled. Built-in types (maps, slices, channels) and functions (such as len, cap, or make) are able to accept and return values of different concrete types, but until Go 1.18, user-defined Go types and functions could not.

If you are accustomed to dynamically typed languages, where types are not evaluated until the code runs, you might not understand what the fuss is about generics, and you might be a bit unclear on what they are. It helps to think of them as “type parameters.” So far in this book, you’ve seen ...

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