Go course Lesson 3 of 6

Go from zero: zero is a real value

A var with no value is not empty of meaning. A blank order has an empty name and 0 cents. The program prints "" $0.00.

Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.

Back to top

If you declare a name and do not assign it, Go stores the zero value of the type. For an int that is 0. For a string that is empty text. Zero is a real value. A blank order is not an error from the language. It is a $0.00 charge with no drink name, unless your program refuses to print it.

Nothing is an empty slot#

Go will not leave a name uninitialized. If you declare cents and do not assign it, the memory is the zero of int, which is 0. A string's zero is the empty string, a bool's zero is false, a pointer's zero is nil, and a struct's zero is a struct of zeros. Zero is a value you can print, pass, and compare. It becomes a bug only when your program decided that 0 means "missing" and then charged it anyway. The language will not make that decision for you.

Declared, and already a blank order
  1. namestring(empty)
  2. centsint0
package main

import "fmt"

func main() {
    var name string
    var cents int
    fmt.Printf("%q $%d.%02d\n", name, cents/100, cents%100)
}
"" $0.00

Read the zero before you charge it#

var name string makes name and stores "". var cents int makes cents and stores 0. %q prints the name in quotes, so an empty drink is visible. The dollars print as $0.00. Without the quotes, the empty name would look like a missing column and you might still charge nothing, or charge the next line by mistake.

A bool's zero is false. A pointer's zero is nil. A struct's zero is a struct whose fields are themselves zero: an Item you did not fill has Name == "" and Cents == 0. That item is usable. Label would print $0.00 with a blank name. If an order with no name is a bug, check the field before you print the label. Do not wait for Go to complain. It will not.

Zero is allowed to be the answer#

A bill that has not been started should be 0 cents. A name that has not been set should be empty. The mistake is treating every 0 as a failure, or treating 0 as safe to charge. The next lesson meets a zero that is not safe to write into: a map you have not made.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.