1

What does this code snippet do?

var i int
_ = i

I understand the use of "_" as a blank identifier, but what does the second line in the above achieve?

Here is an example from the etcd GitHub repository: etcd

savx2
  • 1,011
  • 2
  • 10
  • 28
  • 4
    Nothing. It assigns a value to the blank identifier. Also note that that's an underscore in the left-hand side (LHS), not right-hand side (RHS). – Adrian May 18 '18 at 15:38
  • The statement causes the variable `i` to be used with no other effects. Without seeing the larger context, it's not possible to determine if that's the purpose used here. – Charlie Tumahai May 18 '18 at 15:41
  • I'm trying to think when you might see this.... The only thing I can think of is when you're calling a function that returns an `error` and you want to explicitly disregard that error no matter its result. – Adam Smith May 18 '18 at 15:41
  • I added a link to where I found this. – savx2 May 18 '18 at 15:47

3 Answers3

5

The code is machine generated. The generator added the statements _ = i to avoid unused variable declarations in the case where there's nothing to marshal.

The author of the code generator probably found it easier to add the blank assignment statements than to omit the variables when not needed.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
3

I would guess you might do this to stop go complaining about an unused variable

It would be better to not declare the variable at all

Vorsprung
  • 32,923
  • 5
  • 39
  • 63
  • I think you are right, it is as simple as that. So far I haven't seen another use case for this. – Lucas May 18 '18 at 15:52
  • 2
    This is definitely what it is, since OP posted the code where he found it (defining two variables, then defining them based on a handful of conditionals so neither of them *need* be used for anything) – Adam Smith May 18 '18 at 15:53
  • Right, after reading the code it becomes clear... since 'i' is defined but MIGHT not be used if conditions are not met, it is the correct thing to do to declare it like this. – Lucas May 18 '18 at 16:00
  • @FRECIA If there's a code path where the variable can be used (as there is in the code linked by OP), then the compiler does not consider the variable as unused. The evaluation of the conditions at runtime does not play into this. – Charlie Tumahai May 21 '18 at 00:26
0

Note, sometimes the underscore is used in imports so that the init() code of a package will get executed, however there is no need to call functions in that package.

This is often a technique applied for image processing to register image handlers.

See A use case for importing with blank identifier in golang

Spangen
  • 4,420
  • 5
  • 37
  • 42