Home >Backend Development >Golang >Global variable assignment behavior in ':='
php editor Xiaoxin will introduce to you the global variable assignment behavior in ":=". In earlier versions of PHP, assignment to global variables needed to be declared using the keyword "global". However, since PHP version 7.4 introduced the new syntax ":=" for global variable assignment, we can assign values to global variables more concisely, eliminating the step of using the "global" keyword. This new feature not only improves the readability and maintainability of the code, but also reduces the amount of unnecessary code and allows us to operate global variables more conveniently. Let’s take a closer look at this new feature!
Even if the code uses :=
in the main function
scope, the global level
is still assigned Value from the getlevel()
return value. Can someone explain how this is predictable and documented behavior using a language specification. My idea was to read the spec better, but I obviously didn't do that.
Code: https://go.dev/play/p/4pz0vl-2snn
65bcfadd4058Output: -
info <nil> print: info
In your example, :=
actually introduces a new local variable named level
which is According to the specification, because global scope is different from any function scope:
Short variable declarations may redeclare variables, provided they were originally declared with the same type in the same block (or argument list, if the block is a function body).
The reason you are seeing the behavior described is that none of your uses of level
actually refer to global variables. The usage in main
is the local variable added from :=
, and the usage in print
is the function parameter. Remove the parameters (in declaration and call site) and you will see print
print an empty string after print:
.
The above is the detailed content of Global variable assignment behavior in ':='. For more information, please follow other related articles on the PHP Chinese website!