当前位置:网站首页>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/
边栏推荐
- Spingboot reads the parameter values in the YML configuration file
- Gin security -3: fast implementation of CSRF verification
- Advantages of token mechanism over cookie mechanism
- ntpupdate. tencentyun. Com has been eliminated
- How to evaluate performance optimization? Covering too much knowledge?
- How PMO uses two dimensions for performance appraisal
- JS regular ignore case
- Pathname attribute of link a object
- On line project LAN on-line software use ----phpstudy
- Short video intelligent audit software intelligent audit or manual audit
猜你喜欢

I am 30 years old, no longer young, and have nothing
Application of JDBC in performance test

3000 frame animation illustrating why MySQL needs binlog, redo log and undo log

Steps for formulating the project PMO strategic plan

How PMO uses two dimensions for performance appraisal

What are the main dimensions of PMO performance appraisal?

Applet development framework recommendation

Four aspects of PMO Department value assessment

JS advanced programming version 4: generator learning
随机推荐
游戏安全丨喊话CALL分析-写代码
3000 frame animation illustrating why MySQL needs binlog, redo log and undo log
Global and Chinese markets for e-cigarettes and tobacco vapors 2022-2028: Research Report on technology, participants, trends, market size and share
同花顺开户是安全的吗?
Excel text function
Memory patch amsi bypass
. Net Core 3. X MVC built-in log extension log4net
Command line add user set password never expires add remote group add administrator group
Process injection
【etcd】etcd使用与集群搭建
JS mailbox regular expression
How PMO uses two dimensions for performance appraisal
How to process the text of a picture into a table? Can the text in the picture be transferred to the document?
Pathname attribute of link a object
What software is safe to use to fight new debts? What are the new bond platforms
Advantages of short video automatic audit? What are the difficulties of manual audit?
What is the main content of short video audit? What is illegal?
Thinking about distributed system consensus
How to deal with unclear pictures? How to deal with color balance?
More than 1200 phishing kits that can intercept 2fa detected in the field