kerokero
(Kerokero)
March 7, 2019, 12:16pm
1
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?
NobbZ
(Norbert Melzer)
March 7, 2019, 12:37pm
2
Whats the problem with the first? The observable effect of both snippets should be the same
kerokero
(Kerokero)
March 7, 2019, 12:44pm
3
See here: https://play.golang.org/p/mo-cEC4uIhA
It won’t compile because I need to assign “err” for the first time
kerokero
(Kerokero)
March 7, 2019, 12:46pm
4
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)
}
}
NobbZ
(Norbert Melzer)
March 7, 2019, 12:53pm
5
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.
SolarLune
(Solar Lune)
March 7, 2019, 5:43pm
6
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.
iegomez
(Ignacio Gómez)
March 7, 2019, 6:05pm
7
No , this will shadow length
by declaring it in the inner scope as in this example: https://play.golang.org/p/2vdMbSjgrLW
1 Like
kerokero
(Kerokero)
March 7, 2019, 6:21pm
8
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.
SolarLune
(Solar Lune)
March 7, 2019, 7:02pm
9
Ah, whoops, you’re both right. Guess you’ll have to use that solution and declare the error beforehand.
system
(system)
Closed
June 5, 2019, 7:02pm
10
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.