Home > front end >  how to use a `switch` statement in Go
how to use a `switch` statement in Go

Time:12-22

package main

import "fmt"

func main() {

    var age int
    fmt.Scanf("%d", &age)

    // Code your switch or if...else-if statement here.
    
    switch age {
    case 1:
        age <= 14
        fmt.Println("Toy Story 4")
    case 2:
        age <= 18
        fmt.Println("The Matrix")
    case 3:
        age <= 25
        fmt.Println("John Wick")
    case 4:
        age <= 35
        fmt.Println("Constantine")
    case 5:
        age > 35
        fmt.Println("Speed")
    default:
        fmt.Println("Error: Unknown age")
    }
}

I get a yellow marker in the IDE for the scanf, flagging an unhandled error. Also, all the cases have the first line flagged red, preventing to compile. The error I get is age <= 14 is evaluated, but not used. The same is true for all statements. I have searched the web and looked at examples, and from what I can see, the code is, as the materials and examples state. Here is a screenshot from Go Land (JetBrains):

Does anybody have an idea? Also, if you answer, please keep in mind, that this is a lesson from a Go course and I have to use scanf. I could change the switch to an else if, which is likely going to fix the issue, but I am kind of curious, about why this is happening and how I can fix it. :)

CodePudding user response:

age <= 14 is not a valid Go expression, though it could be used as part of one. Go is very particular about all values being consumed.

This isn't the correct way to write a case with <= operators.

    switch age {
    case 1:
        age <= 14
        fmt.Println("Toy Story 4")
    ...
    }

That case matches if the value of age is 1. You want to use a switch style like this:

switch {
case age <= 14:
   fmt.Println("Toy Story 4")
case age <= 18:
   ...
...
}

CodePudding user response:

To add to what Daniel wrote — basically the switch statement (unless it's a type switch but let's not digress) has two forms:

switch { // note the absense of any expression here
  case bool_expr_1:
    ...
  case bool_expr_2:
    ...

and

switch any_expr {
  case value_to_match_1:
    ...
  case value_to_match_2:
    ...

In the first form, expressions in each case branch are evaluated top-to-bottom, and the first which evaluates to true, "wins"—that is, the code in that branch is executed.
In the second form, the expression is evaluated to produce a value which is then compared exactly with the value in each case branch.

You have tried to sort-of combine both forms, which won't work.
You might have thought that those numbers in the case branches is the order of how the branches should be checked but no, that's not it.

  • Related