回答

收藏

Go中函数体外的非声明语句

技术问答 技术问答 244 人阅读 | 0 人回复 | 2023-09-12

我正在提供 JSON 或 XML 格式数据 API 构建 Go 库。- }! M6 Q; f) a. Z/ l4 Z
这个 API 要求我session_id每15 请求一次,并在调用中使用。2 X- \, d9 O6 f& |3 @- @% b' O
    foo.com/api/[my-application-id]/getuserprofilejson/[username]/[session-id]foo.com/api/[my-application-id]/getuserprofilexml/[username]/[session-id]9 X! x* Z4 q  d$ o
在我的 Go 库里,我试着在那里main()func创建一个变量,并计划为每个 API 调用 ping 一个值。如果值是 nil 或者是空的,请求新的会话 ID 等等。
6 x. M( n% s" N* H; }
    package apitestimport  "fmt")test := "This is a test."func main()      fmt.Println(test)    test = "Another value"    fmt.Println(test)}
    ( x: g3 N. t9 i+ Z3 ?; d
声明全局可访问变量,但不一定是常用 Go 的方法是什么?4 v5 o# }6 L% g, e$ j: T6 O. U
我的test变量需要:! r  P. V! p0 p) `, v
可以访问自己包里的任何地方。
& {! L# f- A, k6 [8 d7 D多变
                                                               
( b* l  P* g) j9 m, m# E3 H    解决方案:                                                               
6 ]0 |7 @# M2 h$ r* B+ |# m' |9 Z                                                                你需要/ L: p% Y6 [9 A* X7 g" e+ Y" x
    var test = "This is a test"; N, v! F& v. m! Y5 [& F
:= 只适用于函数,小写t只对包可见(未导出)。
/ d3 V  J# M6 I, x- B0 A更彻底的解释
& e' a5 H9 ~3 L- v+ ]- i7 [test1.go; T+ R" l: y% l( C
    package mainimport "fmt"// the variable takes the type of the initializervar 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 receiversfunc 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)}1 t3 U& Z0 s! L9 K
test2.go2 }, A2 A+ N7 b% }1 ~/ N( L
    package mainfunc changeTest(newTest string)    test = newTest}- u( s) K3 n4 A, _' c. X/ g2 r* V( X
输出
5 r/ z+ Z+ S* R5 x' ]( L
    testingSomething ElseType can be inferred
    ) z/ w* \# B$ ]! V2 T
或者,对于更复杂的包初始化或设置包所需的任何状态,GO 提供了一个 init 函数。
$ h; b9 e2 {+ G+ S4 @
    package mainimport  "fmt")var test map[string]intfunc init()      test = make(map[string]int)    test["foo"] = 0    test["bar"] = 1}func main()      fmt.Println(test) // prints map[foo:0 bar:1]}5 R" X* L5 C! a) n
init 将在 main 运行前调用。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则