Set variables per OS


(G Voice Gd) #1

Any hints on how to set a bunch of variables per GOOS?
The switch statement fails to define var(s), whether in main() or in init() block.

	switch os := runtime.GOOS; os {
	case "windows", "arm64":
		var (
			foo = "bar1"
			// ... set more vars ...
		)
	case "arm":
		var (
			foo = "bar2"
			// ... set more vars ...
		)
	default:
		var (
			foo = "bar3"
			// ... set more vars ...
		)
	}

	fmt.Printf("%#v \n", foo) // FAILs: "undefined: foo"

(Jay Ts) #2

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: https://play.golang.org/p/olzVrX2fCS4

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: https://play.golang.org/p/bzBgDmW-8zT

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: https://play.golang.org/p/4m-4xaeVOrb


(George Calianu) #3

Well, using switch is not so idiomatic and complicated if you will use in the future many variables. A better method is using conditional compilation and files for every architecture or operating system. Take a look over Dave Cheney article to see how to do this.

https://dave.cheney.net/2013/10/12/how-to-use-conditional-compilation-with-the-go-build-tool


(G Voice Gd) #4

Scope! Got it. So, a stand-alone var declaration, instead of at the switch/default case, and then reset per condition in the switch, instead of declare. Thanks.