What's wrong with this code?

Years ago I tried learning a little Japanese, and the first part was to learn to write the hiragana alphabet. I had the same feeling! I had to practice writing every character over and over. I felt like I was 5 years old and just learning to write.

Fortunately, any programming language is a lot easier to learn than Japanese. So don’t worry.

About the code snippet, you didn’t get the whole thing. Try this:

if i, err := strconv.Atoi("42"); err == nil { /* statements */ }

This is an example of a more complicated if/then construct. It is equivalent to

i, err := strconv.Atoi("42")
if err == nil { /* statements */ }

Go allows you to insert a statement before the boolean expression of the if statement. It’s just to allow for more concise code. (Personally, I think it’s best to avoid using it, except for very simple cases.)

The first line is like this:

x, y = 1, 2

which sets x to 1 and y to 2. It’s called a tuple assignment. It’s nearly the same as

x = 1
y = 2

But when you have a function that returns multiple values, you have to use a tuple assignment to store those values in variables. So

i, err := strconv.Atoi("42")

results in the string "42" being converted into an int and stored in i, and err will be something other than nil if Atoi() ran into a problem. It’s a good programming practice to always (or at least usually) check for errors and handle them.

Is that what you needed as an explanation?

1 Like