Thursday, May 16, 2024
HomeGolangThis swap assertion compiles. Ought to it's allowed? - Technical Dialogue

This swap assertion compiles. Ought to it’s allowed? – Technical Dialogue


I used to be offered an fascinating gotcha with the Go swap assertion in the present day.

Take into account the next

package deal important

import "fmt"

func f() bool {
  return false
}

func important() {
  swap f()
  {
  case false:
    fmt.Println(1)
  case f():
    fmt.Println(2)
  case true:
    fmt.Println(3)
  default:
    fmt.Println(4)
  }
}

This prints 3.

The gotcha (which most editors received’t catch) is having the curly brace on the subsequent line after the swap assertion. I’m questioning why that is allowed in any respect? And if these case statements are nonetheless tied to the swap assertion that precede them.

Thanks

I’ve by no means seen any bug brought on by one thing like this in the actual world. And in the actual world, tooling will go fmt your code. Attempt pasting this into the go playground for instance and your drawback will turn into obvious as quickly as you click on “run” (which codecs your code as effectively). From a tour of go:

Go’s swap is just like the one in C, C++, Java, JavaScript, and PHP, besides that Go solely runs the chosen case, not all of the circumstances that comply with. In impact, the break assertion that’s wanted on the finish of every case in these languages is supplied robotically in Go. One other essential distinction is that Go’s swap circumstances needn’t be constants, and the values concerned needn’t be integers.

Like I stated – I’ve by no means seen a bug brought on by one thing like what you’ve written above. Nonetheless, I’ve seen a LOT of bugs that have been prevented in go on account of the truth that it implicitly provides break statements. Anyway, in the event you run your code on the go playground you’ll see what is going on. And in essence your code is similar as swap and not using a situation:

Swap and not using a situation is similar as swap true.

See additionally:

https://gobyexample.com/swap

I’m not a “decompile” professional vut i assume than a swap assertion
is a simply “shorthand” strategy to write a bunch of nested if…else…if
this code

 swap f(); {
case false:
    fmt.Println(1)
case f():
    fmt.Println(2)
case true:
    fmt.Println(3)
default:
    fmt.Println(4)
}

it’s operating as :

 f()
if false {
fmt.Println(1)
} else if f() {
fmt.Println(2)
} else if true {
fmt.Println(3)
} else {
fmt.Println(4)
}

Simply add an Println to f perform to examine what number of instances is executed (2 instances)

func f() bool {
 fmt.Println("f() Referred to as")
return false
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments