Reader small image

You're reading from  Go Programming - From Beginner to Professional - Second Edition

Product typeBook
Published inMar 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781803243054
Edition2nd Edition
Languages
Right arrow
Author (1)
Samantha Coyle
Samantha Coyle
author image
Samantha Coyle

Samantha Coyle, a Software Engineer at Diagrid, specializes in Go for cloud-native developer tooling, abstracting application development challenges. Committed to Open Source, she contributes to projects like Dapr and Testcontainers. She boasts a rich history in retail computer vision solutions and successfully stabilized industrial edge use cases with testing and diverse deployments for biopharma data pipelines. Her expertise extends to being CKAD certified and reviewing Go textbooks. She is passionate about empowering early-career, diverse professionals. Samantha is in a family of gophers, and enjoys GopherCon with her brother and identical twin sister. She's a seasoned speaker, having presented at various conferences, including GopherCon.
Read more about Samantha Coyle

Right arrow

Core Types

Overview

This chapter aims to show you how to use Go’s basic core types to design your software’s data. We’ll work through each type to show what they are useful for and how to use them in your software. Understanding these core types provides you with the foundation required to learn how to create complex data designs.

By the end of this chapter, you will be able to create variables of different types for Go programs and assign values to variables of different types. You will learn how to identify and pick a suitable type for any programming situation. You will also write a program to measure password complexity and implement empty value types.

Technical requirements

For this chapter, you'll require Go version 1.21 or higher. The code for this chapter can be found at: https://github.com/PacktPublishing/Go-Programming-From-Beginner-to-Professional-Second-Edition-/tree/main/Chapter03.

Introduction

In the previous chapter, we learned how to use if, if-else, else-if, switch, case, continue, break, and goto in Go.

Go is a strongly typed language, and all data is assigned a type. That type is fixed and can’t be changed. What you can and can’t do with your data is constrained by the types you assign. Understanding exactly what defines every one of Go’s core types is critical to success with the Go language.

In later chapters, we’ll talk about Go’s more complex types, but those types are built on the core types defined in this chapter.

Go’s core types are well-thought-out and easy to understand once you understand the details. Having to understand the details means Go’s type system is not always intuitive. For example, Go’s most common number type, int, may be either 32 bits or 64 bits in size depending on the computer used to compile the code.

Types are needed to make data easier for humans to work with...

True and false

True and false logic is represented using the Boolean type, bool. Use this type when you need an on/off switch in your code. The value of a bool instance can only ever be true or false. The zero value of a bool instance is false. A “zero value” refers to the default value that a variable takes when it’s declared without an explicit initial value.

When using a comparison operator such as == or >, the result of that comparison is a bool value.

In this code example, we use comparison operators on two numbers. You’ll see that the result is a bool value:

package main
import "fmt"
func main() {
  fmt.Println(10 > 5)
  fmt.Println(10 == 5)
}

Running the preceding code shows the following output:

true
false

Exercise 3.01 – Program to measure password complexity

An online portal creates user accounts for its users and accepts passwords that are only 8 to 15 characters long. In this exercise...

Numbers

Go has two distinct number types – integers, also known as whole numbers and floating-point numbers. The floating-point number type allows whole numbers and numbers that contain fractions of a whole number.

1, 54, and 5,436 are examples of whole numbers. 1.5, 52.25, 33.333, and 64,567.00001 are all examples of floating-point numbers.

Note

The default and empty value for all number types is 0.

Next, we’ll start our number journey by looking at integers.

Integers

Integer types are classified in two ways, based on the following conditions:

  • Whether or not they can store negative numbers
  • The smallest and largest numbers they can store

Types that can store negative numbers are called signed integers. Types that can’t store negative numbers are called unsigned integers. How big and small a number each type can store is determined by how many bytes of internal storage they have.

Here is an excerpt from the Go language specification...

byte

The byte type in Go is just an alias for uint8, which is a number that has eight bits of storage. In reality, byte is a significant type, and you’ll see it in lots of places. A bit is a single binary value – a single on/off switch. Grouping bits into groups of eight was a common standard in early computing and became a near-universal way to encode data. 8-bits have 256 possible combinations of “off” and “on,” so uint8 has 256 possible integer values from 0 to 255. All combinations of on and off can are represented with this type.

You’ll see byte used when reading and writing data to and from a network connection and when reading and writing data to files.

With this, we’re all done with numbers. Now, let’s look at how Go stores and manages text.

Text

Go uses a single string type to represent text.

When you write text to a string variable it’s called a string literal. There are two kinds of string literals in Go:

  • Raw – defined by wrapping text in a pair of `
  • Interpreted – defined by surrounding the text in a pair of "

With raw literals, what ends up in your variable is precisely the text that you see on the screen. With interpreted literals, Go scans what you’ve written and then applies transformations based on its own set of rules.

Here’s what that looks like:

package main
import "fmt"
func main() {
  comment1 := `This is the BEST
thing ever!`
  comment2 := `This is the BEST\nthing ever!`
  comment3 := "This is the BEST\nthing ever!"
  fmt.Print(comment1, "\n\n")
  fmt.Print(comment2, "\n\n")
  fmt.Print(comment3, "\n")
}

Running the preceding code...

The nil value

nil is not a type but a special value in Go. It represents an empty value of no type. When working with pointers, maps, and interfaces (we’ll cover these in the next chapter), you need to be sure they are not nil. If you try to interact with a nil value, your code will crash.

If you can’t be sure whether a value is nil or not, you can check it like this:

package main
import "fmt"
func main() {
  var message [] string
  if message == nil {
    fmt.Println("error, unexpected nil value")
    return
  }
  fmt.Println(message)
}

Running the preceding code displays the following output:

error, unexpected nil value

In the preceding example, we declared the message variable as a slice of strings, but did not initialize it with any values. As such, the value of message is nil.

Activity 3.01 – Sales tax calculator

In this activity, we create...

Summary

In this chapter, we took a big step in working with Go’s type system. We took the time to define what types are and why they are needed. We then explored each of the core types in Go. We started with the simple bool type, and we were able to show how critical it is to everything we do in our code. We then moved on to the number types. Go has lots of types for numbers, reflecting the control that Go likes to give developers when it comes to memory usage and accuracy. After numbers, we looked at how strings work and how they are closely related to the rune type. With the advent of multi-byte characters, it’s easy to make a mess of your text data. Go has provided powerful built-in features to help you get it right. Lastly, we looked at nil and how you use it within Go.

The concepts you’ve learned in this chapter have armed you with the knowledge needed to tackle Go’s more complex types, such as collections and structs. We’ll be looking at...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Go Programming - From Beginner to Professional - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781803243054
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Samantha Coyle

Samantha Coyle, a Software Engineer at Diagrid, specializes in Go for cloud-native developer tooling, abstracting application development challenges. Committed to Open Source, she contributes to projects like Dapr and Testcontainers. She boasts a rich history in retail computer vision solutions and successfully stabilized industrial edge use cases with testing and diverse deployments for biopharma data pipelines. Her expertise extends to being CKAD certified and reviewing Go textbooks. She is passionate about empowering early-career, diverse professionals. Samantha is in a family of gophers, and enjoys GopherCon with her brother and identical twin sister. She's a seasoned speaker, having presented at various conferences, including GopherCon.
Read more about Samantha Coyle