GO中函数体外的非声明语句 [英] Non-declaration statement outside function body in Go
本文介绍了GO中函数体外的非声明语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为提供JSON或XML格式数据的API生成Go库。
此接口要求我每隔15分钟左右请求一个session_id
,并在调用中使用。例如:
foo.com/api/[my-application-id]/getuserprofilejson/[username]/[session-id]
foo.com/api/[my-application-id]/getuserprofilexml/[username]/[session-id]
在我的Go库中,我试图在main()
函数之外创建一个变量,并打算为每个API调用ping一个值。如果该值为空或空,则请求新会话ID,依此类推。
package apitest
import (
"fmt"
)
test := "This is a test."
func main() {
fmt.Println(test)
test = "Another value"
fmt.Println(test)
}
声明全局可访问变量但不一定声明常量的惯用GO方式是什么?
我的test
变量需要:
- 可以从其自己包中的任何位置访问。
- 可变
推荐答案
您需要
var test = "This is a test"
:=
仅适用于函数,小写"t"使其仅对包可见(未导出)。
更详细的说明
test1.go
package main
import "fmt"
// the variable takes the type of the initializer
var test = "testing"
// you could do:
// var test string = "testing"
// but that is not idiomatic GO
// Both types of instantiation shown above are supported in
// and outside of functions and function receivers
func main() {
// Inside a function you can declare the type and then assign the value
var newVal string
newVal = "Something Else"
// just infer the type
str := "Type can be inferred"
// To change the value of package level variables
fmt.Println(test)
changeTest(newVal)
fmt.Println(test)
changeTest(str)
fmt.Println(test)
}
test2.go
package main
func changeTest(newTest string) {
test = newTest
}
输出
testing
Something Else
Type can be inferred
或者,对于更复杂的包初始化或设置包所需的任何状态,GO提供了init函数。
package main
import (
"fmt"
)
var test map[string]int
func init() {
test = make(map[string]int)
test["foo"] = 0
test["bar"] = 1
}
func main() {
fmt.Println(test) // prints map[foo:0 bar:1]
}
将在运行Main之前调用Init。
这篇关于GO中函数体外的非声明语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文