Assign variable inside condition

I’d like to write this:

length := 10
if len(os.Args) == 2 {
       length, err = strconv.Atoi(os.Args[1])
		if err != nil {
			log.Fatal(err)
		}
	}

but I’m forced to write this:

length := 10
if len(os.Args) == 2 {
        l, err := strconv.Atoi(os.Args[1])
	if err != nil {
			log.Fatal(err)
	}
	length = l
}

Am I missing something?

Whats the problem with the first? The observable effect of both snippets should be the same

See here: https://play.golang.org/p/mo-cEC4uIhA
It won’t compile because I need to assign “err” for the first time

Well, I can also do this:

	length := 10
	var err error
	if len(os.Args) == 2 {
		length, err = strconv.Atoi(os.Args[1])
		if err != nil {
			log.Fatal(err)
		}
	}

I assumed you didn’t copy that part. Sadly I have an err to spare in about every other function when I have to write go and reuse it.

Change this:

length, err = strconv.Atoi(os.Args[1])

to this:

length, err := strconv.Atoi(os.Args[1])

As you’ve already created the length variable, but are creating the err variable right there in that line. Therefore, you need to add a “:” to declare the variable as well.

No, this will shadow length by declaring it in the inner scope as in this example: https://play.golang.org/p/2vdMbSjgrLW

1 Like

As @iegomez said, it introduces a subtle bug (well, in my snippet it won’t compile, but that’s only luck).
I think Assign variable inside condition is the cleanest solution, though I don’t quite like it.

Ah, whoops, you’re both right. Guess you’ll have to use that solution and declare the error beforehand.

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