Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我无法找到所需的解决方案。我想调用一个函数并想使用在该函数中声明的某个变量(我不想返回该变量)。我只想让它全球化。
func foo(){ temp:=30 } func main(){ foo() // How to use temp without returning or without declaring it outside foo and main }
你不能。您只能在包范围内声明一个包变量(又名全局变量)。您可以从函数内部对其进行修改,但不能在函数内部声明它。这是因为引用该变量的任何其他内容都必须在编译时解析该引用。否则,当Bar()尝试在Foo()声明之前引用变量时会发生什么?这会破坏 Go 保证的编译时安全性。
Bar()
Foo()
也就是说,解决方案很简单;只需在包范围内声明它。不清楚为什么你不想这样做的问题 - 如果你想要一个全球性的,那就是你所做的。