3 Data types

 

This chapter covers

  • Common mistakes related to basic types
  • Fundamental concepts for slices and maps to prevent possible bugs, leaks, or inaccuracies
  • Comparing values

Dealing with data types is a frequent operation for software engineers. This chapter delves into the most common mistakes related to basic types, slices, and maps. The only data type that we omit is strings because a later chapter deals with this type exclusively.

3.1 #17: Creating confusion with octal literals

Let’s first look at a common misunderstanding with octal literal representation, which can lead to confusion or even bugs. What do you believe should be the output of the following code?

sum := 100 + 010
fmt.Println(sum)

At first glance, we may expect this code to print the result of 100 + 10 = 110. But it prints 108 instead. How is that possible?

In Go, an integer literal starting with 0 is considered an octal integer (base 8), so 10 in base 8 equals 8 in base 10. Thus, the sum in the previous example is equal to 100 + 8 = 108. This is an important property of integer literals to keep in mind—for example, to avoid confusion while reading existing code.

Octal integers are useful in different scenarios. For instance, suppose we want to open a file using os.OpenFile. This function requires passing a permission as a uint32. If we want to match a Linux permission, we can pass an octal number for readability instead of a base 10 number:

file, err := os.OpenFile("foo", os.O_RDONLY, 0644)

3.2 #18: Neglecting integer overflows

3.2.1 Concepts

3.2.2 Detecting integer overflow when incrementing

3.2.3 Detecting integer overflows during addition

3.2.4 Detecting an integer overflow during multiplication

3.3 #19: Not understanding floating points

3.4 #20: Not understanding slice length and capacity

3.5 #21: Inefficient slice initialization

sitemap