Golang Global Variable access

本文解答了如何在Go语言的不同包或文件间访问由main.go初始化的全局变量的问题,并提供了两种实现方法:通过导出变量并直接引用或者通过传递变量的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

golang 中全局变量的问题。

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

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 Answers

up vote 33down voteaccepted

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

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! – Nighthee Jan 27 '16 at 14:05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值