Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 为什么可以从另一个函数访问包级指针变量?_Go - Fatal编程技术网

Go 为什么可以从另一个函数访问包级指针变量?

Go 为什么可以从另一个函数访问包级指针变量?,go,Go,在下面的代码中,router是指向结构的包级别变量。此指针在main函数中初始化。但是它不能在同一个包中的另一个函数中访问。如果我对另一个int指针执行相同的操作,则可以在initializeRoutes函数中访问该指针 go版本go1.14.6 windows/amd64 package main import ( "github.com/gin-gonic/gin" "net/http" ) var router *gin.Eng

在下面的代码中,
router
是指向结构的包级别变量。此指针在
main
函数中初始化。但是它不能在同一个包中的另一个函数中访问。如果我对另一个int指针执行相同的操作,则可以在initializeRoutes函数中访问该指针

go版本go1.14.6 windows/amd64

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)


var router *gin.Engine

func main() {
    router := gin.Default()
    router.LoadHTMLGlob("templates/*")
    initializeRoutes()
    router.Run()
}

func initializeRoutes() {
    fmt.Println(router)
    // here the router is nil
}


您正在使用
main
中的
:=
运算符隐藏全局变量
router

var router *gin.Engine

func main() {
    router := gin.Default()  // make a new variable called "router", shadowing the global var
    router.LoadHTMLGlob("templates/*")
    initializeRoutes()
    router.Run()
}

func initializeRoutes() {
    fmt.Println(router)  // this doesn't know about main's "router", so sees the global var
}
要解决此问题,请不要使用
:=
运算符。改为使用普通旧分配:

var router *gin.Engine

func main() {
    router = gin.Default()  // assigns to the global var
    router.LoadHTMLGlob("templates/*")
    initializeRoutes()
    router.Run()
}

func initializeRoutes() {
    fmt.Println(router)
}

有关此操作的更简单示例,请参阅。

“但它不能在同一软件包中的其他函数中访问。”--是的,它可以。为什么你认为它不能?