Chapter 2Go Types Explored

In the last chapter, we were introduced to the basic Go types and syntax. In this chapter we’ll go a little deeper into some of the types, and how to define your own types and interfaces. We’ll also cover how Go lets us use third-party libraries in our software with ease.

Custom Types

While you can’t add your own methods to built-in types, you can create your own types from other types. A common example of this is a ByteSize type, which extends float64 and provides a custom formatted string to represent a size in bytes such as 2 kilobytes or 3.14 megabytes:

const ( KB = 1024 MB = KB * 1024 GB = MB * 1024 TB = GB * 1024 PB = TB * 1024 ) type ByteSize float64 func (b ByteSize) String() string { switch { case b >= PB: ...

Get Level Up Your Web Apps With Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.