Home > Backend Development > Golang > Global variable assignment behavior in ':='

Global variable assignment behavior in ':='

PHPz
Release: 2024-02-09 14:50:25
forward
780 people have browsed it

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!

Question content

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

65bcfadd4058

Output: -

info <nil>
print: info
Copy after login

Workaround

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template