Saltar a contenido

02 - First Real Program

What this session is

About 45 minutes. You'll learn three things: variables (storing data), types (kinds of data), and the expressions you can do with them. By the end you'll have written a program that uses all three.

Why variables exist

Programs do things with data. To do things with data, you have to store it somewhere named, so you can refer to it later.

That's all a "variable" is: a name attached to a piece of data.

A small program with variables

Open your go-learning folder. Create a new file called greet.go. Type this in:

package main

import "fmt"

func main() {
    name := "Alice"
    age := 30
    fmt.Println(name, "is", age, "years old")
}

Run it:

go run greet.go

You should see:

Alice is 30 years old

What's new here

Two lines you haven't seen before:

name := "Alice"
age := 30

Let's unpack name := "Alice":

  • name is the name of a new variable.
  • := is the "create and assign" operator. Read it as "is set to."
  • "Alice" is the value we're putting into it. The double quotes mean it's text (a "string").

So name := "Alice" reads as: "create a variable called name and set it to the text Alice."

age := 30 does the same thing with a number. No quotes around 30 - numbers don't take quotes.

The last line:

fmt.Println(name, "is", age, "years old")

You've seen fmt.Println before. New thing: it can take multiple things separated by commas, and it prints them with spaces in between. We give it four things - the value of name, the text "is", the value of age, and the text "years old". Out comes one line with all four glued together by spaces.

Types: what kind of thing is this?

Every value in Go has a type. The type tells Go what kind of thing it is - text? a number? something else? - and what you can do with it.

You'll meet many types over time. The first three you need to know are:

Type What it holds Example values
int whole numbers (positive, negative, or zero) 0, 42, -7, 1000
string text in double quotes "hello", "", "a long sentence"
bool one of two values: true or false true, false

Notice you didn't have to tell Go that name is a string and age is an int. Go figured it out from the values you gave them - "Alice" has quotes (must be a string), 30 doesn't (must be a number). This is called type inference.

There's a longer way to write the same thing, where you spell out the type:

var name string = "Alice"
var age int = 30

Both forms do the same thing. Use := when you can (it's shorter); save var for cases we'll meet later. But you'll see var in real code, so don't be surprised.

What you can do with numbers

The usual arithmetic works:

x := 10
y := 3
fmt.Println(x + y)   // 13
fmt.Println(x - y)   // 7
fmt.Println(x * y)   // 30
fmt.Println(x / y)   // 3
fmt.Println(x % y)   // 1

That // 13 part is a comment - anything after // on a line is ignored by Go. Comments are how you leave notes for yourself (or future readers) in the code.

Three things to notice:

  • x / y gave 3, not 3.333.... That's because x and y are ints - integers, whole numbers. Integer division throws away the remainder. To get the decimal answer you need a different type (float64), which we'll meet when we actually need it.
  • x % y gave 1. The % operator gives the remainder after division. 10 / 3 is 3 with 1 left over, so 10 % 3 is 1. We'll use this often to test "is this number even?" (n % 2 == 0 is true if n is even).
  • Both operands have to be the same type. You can't x + "hello".

What you can do with strings

You can stick two strings together with +:

greeting := "hello"
name := "world"
message := greeting + ", " + name
fmt.Println(message)   // hello, world

The technical word for "stick two strings together" is concatenate. You'll hear it.

Notice the same symbol + does two different jobs: - Between numbers: addition. - Between strings: concatenation.

This is normal in programming languages. Go uses the type to decide which job to do.

What you cannot do is mix:

n := 5
s := "items: "
fmt.Println(s + n)   // ERROR

Try it. Go will refuse to compile. The error will say something like "invalid operation: s + n (mismatched types string and int)". The fix: turn the number into a string first.

The most-used tool for this is fmt.Sprintf. It's like Println but instead of printing, it builds a string and gives it back to you:

n := 5
s := fmt.Sprintf("items: %d", n)
fmt.Println(s)   // items: 5

The %d is a placeholder that means "put a number here." fmt.Sprintf looks at the first argument (the template) and fills in %d with the value of n.

You'll meet other placeholders: - %d - for numbers. - %s - for strings. - %v - for "any value, use the default representation."

You don't need to memorize them all. When you can't remember, write %v and it'll usually do the right thing.

What you can do with booleans

A bool is just true or false. You'll use them in decisions (next page). For now:

isReady := true
hasPermission := false
fmt.Println(isReady, hasPermission)   // true false

Exercise

Type this in a new file called me.go:

Write a program that:

  1. Has a variable for your name (a string).
  2. Has a variable for your favorite number (an int).
  3. Has a variable for whether it's morning right now (a bool).
  4. Prints a line like: "Hi, I'm Victor, my favorite number is 7, and yes (true) it's morning."

Try it two ways: - First with multiple arguments to fmt.Println (fmt.Println("Hi, I'm", name, ...)). - Then with fmt.Sprintf and %s, %d, %v placeholders, building one big string and printing it once.

Don't skip this. The act of typing is the learning.

What you might wonder

"Why does integer division throw away the remainder?" Because integers can't represent fractional values. 10 / 3 has to give some integer answer - Go picks the closest one that fits, which is 3. If you want 3.333..., you need decimals, which is a different type (float64). We'll meet floats when we need them.

"Why does Go yell at me for mixing strings and numbers?" By design. In some languages, adding a number to a string silently converts the number ("items: " + 5 becomes "items: 5"). That seems nice until you have a bug where you accidentally concatenated when you meant to add. Go refuses on purpose; you have to be explicit about what you want.

"What happens if I never use a variable I declared?" Go won't compile. This is on purpose too - unused variables are usually bugs (you typed the wrong name somewhere). Either use the variable, or delete the line.

Done

You can now: - Make variables and give them values. - Tell apart the three basic types: int, string, bool. - Do arithmetic on numbers. - Stick strings together. - Build a string with fmt.Sprintf and placeholders.

Next page: making your program decide and repeat.

Next: Decisions and loops →

Comments