Variables not available outside if/else, want to avoid multiple error checking

This is the block of a program I have written:

args := os.Args[1:]

if len(args) > 0 {
	csvFile, err := os.Open(args[1])
} else {
	csvFile, err := os.Open("problems.csv")
}

if err != nil {
	log.Fatal(err)
}

As you experts might have noticed, csvFile, err are not available outside the if/else block. But I also want to avoid error checking each time in if/else block (consider having a long if/else).

Is there a golang way to achieve what I’m trying to do?

My suggestion:

args := os.Args[1:]
filename := "problems.csv"
if len(args) > 0 {
	filename = args[1]
}

csvFile, err := os.Open(filename)
if err != nil {
	log.Fatal(err)
}
3 Likes

I agree with @vinid.cuongnd18. Also consider len(args)>1 if you access to args[1].

My suggestion

args := os.Args[1:]
filename := "problems.csv"

if len(args) > 0 {
   filename = args[1]
}

csvFile, err := os.Open(filename)
if err != nil {
	log.Fatal(err)
}

to make ease my codigon I try to use Object Calisthenics (https://williamdurand.fr/2013/06/03/object-calisthenics/)

As I assume you are following gophercises, my solution is more specific to it as it makes argument parsing part painless:

filenamePtr := flag.String("file", "problems.csv", "a csv file with ques,ans")
flag.Parse()

csvFile, err := os.Open(*filenamePtr)
if err != nil {
	log.Fatal(err)
}
1 Like

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