当前位置:网站首页>Go local variables & global variables
Go local variables & global variables
2022-06-23 21:11:00 【Wangxiaoming_ HIT】
local variable
Definition : It's defined in {} The variables inside are local variables
Scope : Only in {} It works inside ; Execute to the defined sentence , Start allocating memory space , Automatically release when leaving the scope - Local variables must be declared inside the function
- In which
{}Internal statement ; Execute to the defined sentence , Start allocating memory , Only in which{}Internal visits , Automatically release when leaving the scope
Look at an example
package main
import "fmt"
func main() {
// It's defined in {} The variables inside are local variables , Only in {} It works inside
// Execute to the sentence of defining variables , Just started allocating space , Automatically release when leaving the scope
// Scope , The scope of the variable
if flag := 3; flag == 3 {
fmt.Println("flag = ", flag)
}
//flag = 4 Can't be in if Outside execution Report errors :undefined: flag Undefined tags
}Global variables
Definition : Variables outside the function are called global variables Scope : Anywhere in the same bag
- A lowercase letter , The whole package can access
- Capitalization , Cross package access
package constant
var A = 12123
var B = map[string]string{}
var c = "xiaoming"
func Init() {
A = 1321312
B["default"] = "default"
}test : The same package can access
package constant
import (
"fmt"
"testing"
)
func TestGlobal(t *testing.T) {
// Global variables are declared outside the function , The entire package can be accessed
// If the global variable is capitalized , Cross package can also access .
fmt.Println(c)
}Execution results :
=== RUN TestGlobal xiaoming --- PASS: TestGlobal (0.00s) PASS
test : Cross package access
package variable
import (
"fmt"
//"go/constant"
"testing"
"/GoProject/main/gobase/constant"
)
func TestGlobal(t *testing.T) {
constant.Init()
fmt.Println(constant.A)
fmt.Println(constant.B["default"])
fmt.Println(constant.c) // Will report a mistake
}Comment out the wrong line , The results are as follows :
=== RUN TestGlobal 1321312 default --- PASS: TestGlobal (0.00s) PASS
The pit to avoid for global variables : For example, a global variable is defined , And then there's the use of := Assign values to global variables , There's a problem . See the following example :
package dbops
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
)
var (
dbConn *sql.DB
err error
)
func init() {
dbConn, err := sql.Open("mysql","root:[email protected](localhost:3306)/server?charset=utf8")
if err != nil{
panic(err.Error())
}
log.Println(dbConn)
}
func main() {
log.Println(" View global variables dbConn:",dbConn)
}The results are as follows :
panic: runtime error: invalid memory address or nil pointer dereference [recovered] panic: runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x0 pc=0x5b0a61]
Far because It uses := Assign values to global variables , The result is that the global variable is not assigned a value nil, init Medium dConn Use := Generated , there dbConn It's a local variable , Global variables dbConn There is no assignment , still nil.
Insert picture description here
Reference material
- https://draveness.me/golang/docs/part2-foundation/ch05-keyword/golang-panic-recover/
边栏推荐
- Cloudbase init considerations
- More than 1200 phishing kits that can intercept 2fa detected in the field
- JS mailbox regular expression
- [JS reverse hundred examples] anti climbing training platform for netizens question 6: JS encryption, environment simulation detection
- Disaster recovery series (VII) -- hybrid cloud public network export disaster recovery construction
- Thinking about distributed system consensus
- Realize vscode to write markdown documents + pictures to be automatically uploaded to Tencent cloud cos
- What is the role of short video AI intelligent audit? Why do I need intelligent auditing?
- Application of JDBC in performance test
- Global and Chinese market of roll up piano 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢

Steps for formulating the project PMO strategic plan

Applet development framework recommendation

Four aspects of PMO Department value assessment

JS advanced programming version 4: generator learning

I am 30 years old, no longer young, and have nothing

What are the main dimensions of PMO performance appraisal?

3000 frame animation illustrating why MySQL needs binlog, redo log and undo log
Application of JDBC in performance test

How PMO uses two dimensions for performance appraisal
随机推荐
手续费佣金低的券商,华泰证券网上开户安全吗
Use of pathinfo/pathname in nodejs
JS regular ignore case
What software is safe to use to fight new debts? What are the new bond platforms
Use of paging components in fusiondesign
Process crash does not generate dump. Configure localdumps
JS advanced programming version 4: generator learning
Encryption and decryption analysis of returned data of an e-commerce app (IV)
CPS 22 January additional incentive rules
Authentication can be as simple as this - use the API gateway to protect your API security
How to build a cloud game platform? Disadvantages of traditional games
打新债到底是用什么软件比较安全?打新债平台有哪些
Steps for formulating the project PMO strategic plan
【5分钟玩转Lighthouse】快速使用长安链
What is the difference between object storage and cloud disk service? What are the functions of cloud disk service?
Dart series: your site is up to you. Use extension to extend classes
Process injection
Customize view to imitate today's headlines and like animation!
Global and Chinese market of microphone racks 2022-2028: Research Report on technology, participants, trends, market size and share
2021 three "myths" of science and technology industry -- yuancosmos, NFT and web 3