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 shows the following output:
error, unexpected nil value
Activity 3.01: Sales Tax Calculator
In this activity, we create a shopping cart application, where sales tax must be added to calculate the total:
- Create a calculator that calculates the sales tax for a single item.
- The calculator...