How to correctly use os.Args in golang?

For another approach, you can wrap the logic in a function:

package main
import "os"

func configPath(a []string) string {
   switch len(a) {
      case 1: return "/etc/buildozer/config"
      default: return os.Args[1]
   }
}

func main() {
   config := configPath(os.Args)
   println(config)
}

this avoids the scoping issue.


Define configPath outside the scope of your if.

configPath := ""

if len(os.Args) > 1 { 
  configPath = os.Args[1] 
  fmt.Println("1") // For debugging purposes 
} else { 
  configPath = "/etc/buildozer/config"
  fmt.Println("2") 
}

Note the 'configPath =' (instead of :=) inside the if.

That way configPath is defined before and is still visible after the if.

See more at "Declarations and scope" / "Variable declarations".