In the following code

Why does case (4==4) not print?

Because when case 3==3 evaluates true the switch is done. Its done after that.

The first correct condition is 3==3. This gets executed then the program exists.

This is from the Go Programming Language Specification:

In an expression switch, the switch expression is evaluated and the case expressions, which need not be constants, are evaluated left-to-right and top-to-bottom; the first one that equals the switch expression triggers execution of the statements of the associated case; the other cases are skipped. If no case matches and there is a “default” case, its statements are executed. There can be at most one default case and it may appear anywhere in the “switch” statement.

So that’s why only one of the fmt.Println() functions ran. It’s possible to get both to run by using a fallthrough statement, but unfortunately, the second will run whether the expression in its case is true or not. For example:

case (3 == 3):
case (4 == 5):
		fmt.Println("also true, does it print?")   // yes, even though 4==5 is false!

Odd, isn’t it? In this type of switch, you may never want to use fallthrough. It’s more commonly used when the switch expression is non-empty, as in this example:

   package main

    import (

    func main() {

    	var letter rune = 'f'
    	switch letter {
    		case 'f':
    			fmt.Printf("The letter is Unicode %U\n",letter)
    		case 'g':
    			fmt.Printf("The letter is either an f or a g\n")
    			fmt.Printf("The letter %c is not an f or a g\n",letter)

Try different values for letter, including 'f', 'g', and anything else (to trigger the default case). Notice that I used a rune type for letter, so you can use any Unicode character (like a :heartpulse: heart symbol or :joy_cat: kitty face - try cutting and pasting those; just remember to put single quotes around them) and the code will still work.

1 Like

Thanks! That really helps ! I think I’m going to save this


Thanks, gentlemen. All of your answers were helpful especially Jayts. Thank you all for your time.
Jayts. I tried f and g and enjoyed the results. I tried the heart pulse but got something like : invalid character… Not sure I put it in the right place. I put it here: var letter rune = :heartpulse:

Hi Cherolyn,

I tried it myself and learned that copying and pasting the Unicode heart from my post doesn’t work. Maybe it needs to be quoted as code:

var letter rune = 💗

Try that. It worked for me just now.

package main
import "fmt"
func main() { fmt.Println("I💗Go") }

Working with Unicode can be a little tricky sometimes.

I did something wrong

Yes, single quotes were missing.

Where should the single quotes go?

Around the heart you assign to the variable, just as in my play-link

1 Like

Cool. That worked. Generally, when do you use single quotes?

For runes.

1 Like

Thanks :slightly_smiling_face:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.