当前位置:网站首页>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/
原网站

版权声明
本文为[Wangxiaoming_ HIT]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112261357286943.html