Go Programming Tutorial

  • Teacher
  • 38 (Registered)
  • (0 Reviews)

Go Programming Tutorial

Controlling your Go program

Like most programming languages you will need to control your application.

In this lesson, we will cover how to control your application using if/then commands, for loops and more.

If Statement

First, we will look at if statements for controlling our program.

Lets look at how to write an if statement in Go.

if {expression} {
  ...
} else {expression} {
  ...
}

Lets look at a full program.

-> git.admintome.com/go-programming-tutorial/ifelse/main.go

package main

import (
  "fmt"
)

func main() {
  level := 25
  var response string
  if level > 20 {
    response = "High level"
  } else if level <= 20 {
    response = "Low level"
  }

  fmt.Printf("Your level is %s.", response)
}

Here we set a string variable called response based on the value of level.

You can put a default else at the end that will act as a catch all.

func main() {
  level := 32
  var response string
  if level > 20 && level < 30 {
    response = "High level"
  } else if level <= 20 {
    response = "Low level"
  } else {
    response = "Super High level"
  }

  fmt.Printf("Your level is %s.", response)
}

Also notice that the first expression is compound in that we have two expressions that must match in order to run the code block immediately following it.

You can use logical ‘and’ which is ‘&&’ and logical ‘or’ which is ‘||’.

Running the code above gives you:

Your level is Super High level.

For Loops

Most looping and iteration is done using for loops in go.

Look at the following code for a basic for loop in go.

package main

import (
  "fmt"
)

func main() {
  for x := 1; x < 4; x++ {
    fmt.Printf("print a line\n")
  }
}

This very similar to other languages like C/C++.

The output of this application will of course print out 3 lines that say “print a line”.

print a line
print a line
print a line

To iterate over a enumerated type like an array we could use a for loop.

-> git.admintome.com/go-programming-tutorial/forloops/main.go

package main

import (
  "fmt"
)

func main() {
  nums := []int{1, 2, 3}
  for x := range nums {
    fmt.Printf("print line %v\n", x)
  }
}

This will output:

print line 0
print line 1
print line 2

There are a few things to note in our for loop.

We are using the range keyword that will be used to iterate our array nums.

Range is a built-in function that returns two values (more on this later in the functions lesson).

Range will return the current index and the value of the range at that index.

For arrays, indices start at 0 so when we run the program as is we see that it starts at 0.

We can alter our for loop to output the value like this:

for x, y := range nums {
    fmt.Printf("print line %v value %v\n", x, y)
}

This gives us the following output.

print line 0 value 1
print line 1 value 2
print line 2 value 3

We don’t really care what the index is in this case.

We can use a special character in go that ignores whatever the value is.

Look at this code.

for _, y := range nums {
    fmt.Printf("print line %v\n", y)
}

This ignores what the index is and sets the y variable to the value at this index.

Running our code we now see:

print line 1
print line 2
print line 3

What about while loops?

In go we use the for statement to act like a while statement.

To use the for statement like a while statement in other languages, you write the statement like this.

-> git.admintome.com/go-programming-tutorial/whilecomposite/main.go

package main

import (
  "fmt"
)

func main() {
  num := 1
  for num <= 3 {
    fmt.Printf("print line %v\n", num)
    num++
  }
}

Notice we have our expression after the for statement.

In our for block we need to increment num in some way.  If we don’t we get an infinite loop.

Notice also that we can increment an integer variable by using the ‘++’ operator just like some other languages.

This is desirable if we have some way to break out of the loop.

Lets write a program that asks for input.

-> git.admintome.com/go-programming-tutorial/input/main.go

package main

import (
  "fmt"
)

func main() {
  var input string
  for {
    fmt.Println("Enter your name:")
    fmt.Scanln(&input)
    if input == "stop" {
      break
    } else {
      fmt.Printf("You Entered: %v\n", input)
    }
  }
}

Here we have an infinite loop.

We ask for input using the “fmt” package’s Scanln function.

We then use an if block to test if the input is equal to ‘stop’.

If it is then we use the break statement to break out of the loop and finish the program.

Switch Statements

Sometimes when writing a program we will need to branch our execution in many different ways depending on the value of a variable.

Take this following bit of code that creates a menu and waits for a response.

fmt.Println("Select an option:")
fmt.Println("1. Add numbers")
fmt.Println("2. Subtract numbers")
fmt.Println("3. Multiply numbers")
fmt.Println("4. Divide numbers")
result, _ := fmt.Scanln()
if result == 1 {
  // do addition
} else if result == 2 {
  // do subtraction
} else if result == 3 {
  // do multiplication
} else if result == 4 {
  // do divisions
} else {
  // got back an incorrect response
}

We use a bunch of if/else statements to branch the code depending on which menu option the user selects.

We can simplify the code using the switch statement.

Here is our newly formatted menu using the switch statement.

fmt.Println("Select an option:")
fmt.Println("1. Add numbers")
fmt.Println("2. Subtract numbers")
fmt.Println("3. Multiply numbers")
fmt.Println("4. Divide numbers")
switch result, _ := fmt.Scanln(); result {
case 1:
    // do addition
case 2:
    // do subtraction
case 3:
    // do multiplication
case 4:
    // do division
default:
    // got back an incorrect response
}

Exercises

4-1.  Write an application that prints a different greeting depending on the value of a name variable using if/then statements.

4-2.  Write an application that takes an array of the months and using a for statement prints out all the months.

4-3.  Write an application that counts from 1 to 10 using the for loop as a while loop.

4-4.  Write an application that utilizes your own menu.

 

 

 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *