Go course Lesson 1 of 6

Go from zero: a name has a type

A Go name has a type. name is a string, cents is an int, and ready is a bool. The program prints latte $4.50 ready.

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

A name in Go holds one kind of value. A cup label needs three. name is a string, so it holds the drink. cents is an int, so it holds the price as a whole number of cents. ready is a bool, so it holds whether you can hand the drink over. The type is the promise. You add cents. You print the name. You do not add the name to the bool.

What the compiler is promising#

A type in Go is a compile-time promise about one name. name can only ever hold text. cents can only ever hold an integer. ready can only ever hold true or false. The promise is checked before the program runs, so a later line cannot quietly turn the price into text. When you do need the other representation, you convert it on purpose. This program divides the cents by 100 to show dollars, and the conversion sits on the line that prints the label.

A cup label is three typed values
  1. namestringlatte
  2. centsint450
  3. readybooltrue
package main

import "fmt"

func main() {
    var name string = "latte"
    var cents int = 450
    var ready bool = true
    var status string = "sold out"
    if ready {
        status = "ready"
    }
    fmt.Printf("%s $%d.%02d %s\n", name, cents/100, cents%100, status)
}
latte $4.50 ready

The type is written next to the name#

var name string = "latte" does three things. It makes the name name, it says the type is string, and it stores the drink. var cents int = 450 stores 450 cents, which is $4.50, and the int never holds the decimal point. var ready bool = true stores whether the drink can go out. cents/100 is the dollars. cents%100 is the leftover cents, and %02d prints them as two digits so 50 becomes 50 and 5 would become 05.

You can leave the type out when the value makes it obvious: cents := 450 is still an int. This lesson writes the type so you can see it. Later lessons use := once the type is no longer the point.

What the type refuses#

cents + name does not compile. An int and a string are different types, and Go will not guess that you meant to turn one into the other. That error is the lesson working. The label builds the dollars in the Printf call, where you can see the conversion. The next lesson puts the name and the cents inside one struct and calls a method that returns the same kind of label.

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.