GNU/Linux Programmer's Solver - Conditionals in Go

Guess program in Go. Conditionals, if, switch and constants
PROGRAMMING GUESS GO

Conditionals in Go

package main

import "fmt"

func main () {
     const n int = 42
     var h int = 0
     var v int
     
     fmt.Print ("Guess the number ? ")
     fmt.Scanf ("%d", &v)
     
     if v < 0 {
        fmt.Println ("Only positive numbers")
        return 
     }
     
     if v == n {
        fmt.Println ("Well done!")
     } else {
       fmt.Println ("Keep trying!");
       fmt.Print ("The number is ");
       if v > n {fmt.Println ("LOWER")} else {fmt.Println ("HIGHER")}
       
       if h := v - n; h < 0 { h = -h}
       fmt.Print ("HINT : ")
       if h < 5 { fmt.Println ("TOO HOT!!!")
       } else if h < 10 { fmt.Println ("HOT!!!")
       } else if h < 15 { fmt.Println ("WARM")
       } else { fmt.Println ("COLD")    }
    }
}

Go is quite limited in what it offers in terms of conditional expressions. It simply provides the classic if-else construct without much embellishment. Go does not need to enclose conditions between parentheses or anything like that, although parentheses can be used to indicate the precedence of certain operations with complex conditional expressions. As in most languages, it is perfectly correct to chain a new if-else block in the else clause of any conditional expression.

It does not provide reduced versions of the command like Perl or Python, nor a ternary operator.

DID YOU KNOW….

Go does not offer a function to calculate the absolute value of an integer. The math.Abs function only works with floating-point numbers.

What we can do is precede the conditions with a statement. In the example program we use this to calculate the absolute value.

 if h = v - n; h < 0 {
    h = -h
}

The code above first initializes the value of h and then evaluates the condition. This construction can improve code readability, especially when it comes to error handling. For example, the following code uses initialization to attempt to open a file and immediately check if an error has occurred:

if file, err = os.Open("file"); err == nil {
// OK
} else {
// ERROR
}

But we haven’t talked about files or function return values yet…. Well, when you read about that, the code snippet above will make sense :).

I’M NEW

The position of the parentheses in the else blocks is exactly as indicated in the example. We cannot move them to the previous or next line without generating an error. Go inserts semicolons to automatically separate lines. If the brace before the if is not preceded by else, a semicolon is inserted before else, which generates an error. You can check the this page of the official documentation to check the exact rules under which this occurs.

Go also offers a switch statement, which, in its simplest form, is identical to its namesake in C/C++/Java, that is, the switch command accepts a value and allows us to assign code to each possible value using the keyword case.

However, Go presents certain peculiarities. The first is that it is possible to express several cases in the same case separated by commas:

switch v {
    case 1,2:
        fmt.Println ("One or Two")
    case 3:
        fmt.Println ("Three")
    default:
        fmt.Println("Other")
}

As you can see, it’s not necessary to use the break keyword to prevent the flow of each case from continuing in the following cases, although it is still possible to allow the flow to continue normally using the fallthrough keyword. In other words, in Go, the default behavior is to keep the cases separate, and we have to explicitly indicate if we want to continue in the next case.

switch v {
        case 1,2:
                fmt.Println ("One or Two")
        case 3:
                fmt.Println ("Three")
                fallthrough
        default:
                fmt.Println("Another case and Three case")
}

Another peculiarity is that the expression on which we apply the switch indicates the data type to be used in the cases, which are not limited to integers as in other languages. It is even possible to execute switch on the type of a variable to determine its type at runtime:

Another peculiarity is that the expression on which we apply the switch indicates the data type to be used in the cases, which are not limited to integers as in other languages. It is even possible to execute switch on the type of a variable to determine its type at runtime:

        var i interface{} = b;
        switch t := i.(type) {
        case bool:
                fmt.Println ("Boolean")
        case int:
                fmt.Println ("Integer")
        default:
                fmt.Printf ("Type %T\n", t)
        }

If we do not specify any variable, switch behaves like an if-else block, and therefore we can use expressions in the different cases.

        switch  {
        case (v > 10 && v < 20 ):
                fmt.Println ("greater than 10")
        case (v < 10 && v > 0):
                fmt.Println ("value is less than 10")
        default:
                fmt.Println ("Other")
        }

Using this form, we could have written the hint for our program as follows:

switch {
        case h < 5  : fmt.Println ("TOO HOT!!");
        case h < 10 : fmt.Println ("HOT");
        case h < 15 : fmt.Println ("WARM");
        default     : fmt.Println ("COLD");
}

DID YOU KNOW

Go uses the Scanf function from the fmt package to read and process user input. This function behaves the same as its C counterpart with some extensions. You can check the details here.

Go supports booleans with the bool type and the values true and false. If no value is assigned to a bool variable, it will be initialized with the value false.

Go natively supports constants using the keyword const. Assignment values to constants is done using the assignment operator = . The := operator, which allows declaration and assignment of variables, cannot be used with constants.

Summary

  • Supports if ... [else if] ...[else] ...
  • Supports ternary operator (assignment + condition) if assignment; condition {cmd}
  • Supports booleans: bool
  • Supports switch
  • Supports native constants (const CONSTANT = val)

Related Posts

GNU/Linux Programmer's Solver - Introduction

Programming exercises in 18 Programming Languages

Read

linuxprogramming

GNU/Linux Programmer's Solver - Hello World in Go

Hello World program in Go. Basic structure, comments and string literals

Read

PROGRAMMING GO HELLO WORLD

GNU/Linux Programmer's Solver
Chapter 2 - Conditionals

Conditionals are the may way to add logic to your programs.

Read

PROGRAMMING HELLO WORLD

Return to Home Page