您的位置:首页 > 博客中心 > 数据库 >

Golang Global Variable access

时间:2022-03-06 10:05

golang 中全局变量的问题。

------------------------------------------------------------------

17
1

I‘m fairly new to golang, this should be a simple answer but I‘ve tried searching every where with no luck.

How do I access a global variable that was declared/init in my main.go in a different .go package/file? Keeps telling me that the variable is undefined (I know that global variables are bad but this is just to be used as a timestamp)

in main.go

var StartTime = time.Now()
func main(){...}

trying to access StartTime in a different .go file but keep getting StartTime undefined

  • 2
    Possible duplicate of  –  
  •  
    Is the first letter on the variable name capitalized? –   
  •  
    Yes, it is capitalized, and my go build fails –  
  •  
    are you including all relevant files when running the program? That is, when running the code, are you running go run file1.go file2.go ..etc –   
  •  
    Yes, to be more concise, I have a variable called ‘var StartTime = time.Now()‘ in my main.go But when i try to access StartTime in a different .go of the same directory, it says its undefined, would i have to include "main" in the .go file that im trying to call? –   

2 Answers

33accepted

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time
  •  
    Yep it worked! Thanks! –  
3

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

  •  
    My ‘dif‘ is a restful API and won‘t be called when the program starts but only when its invoked through URL, so i need to put the StartTime in main.go and pass it to dif, you‘re passing it from dif to main, thanks for the try though! –  

本类排行

今日推荐

热门手游