Try this:
package main
import (
"fmt"
"runtime"
)
func main() {
var opsys string
switch runtime.GOOS {
case "windows", "arm64":
opsys = "Microsoft Windows or ARM64"
case "arm":
opsys = "ARM"
case "linux":
opsys = "Linux"
default:
opsys = "other"
}
fmt.Printf("Host system: %#v \n", opsys)
}
At the Go Playground: Go Playground - The Go Programming Language
Go is a block scoped language.
By putting your variable declarations for foo
inside the switch
statement, you can use that foo
only inside of that block. When execution leaves that block, another variable named foo
, if it has been declared, is the one your fmt.Printf()
statement has access to.
Here is a simpler example:
package main
import "fmt"
func main() {
var1 := 2
{
var1 := 3
fmt.Printf("Inside the block, var1 = %d\n",var1)
}
fmt.Printf("Outside the block, var1 = %d\n",var1)
}
This program prints:
Inside the block, var1 = 3
Outside the block, var1 = 2
At the Go Playground: Go Playground - The Go Programming Language
If you don’t understand that, remove the { }
braces on lines 6 and 9, and run the code again. First, you will get an error about redeclaring var1
, so change var1 := 3
to var1 = 3
Then run it again to see it print
Inside the block, var1 = 3
Outside the block, var1 = 3
At the Go Playground: Go Playground - The Go Programming Language