回答

收藏

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

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

我正在提供 JSON 或 XML 格式数据 API 构建 Go 库。" j4 i7 w( c$ A6 ?
这个 API 要求我session_id每15 请求一次,并在调用中使用。4 _) [6 e1 v# U5 Z7 R
    foo.com/api/[my-application-id]/getuserprofilejson/[username]/[session-id]foo.com/api/[my-application-id]/getuserprofilexml/[username]/[session-id]
    2 f# ]4 T; H6 s" ?9 n
在我的 Go 库里,我试着在那里main()func创建一个变量,并计划为每个 API 调用 ping 一个值。如果值是 nil 或者是空的,请求新的会话 ID 等等。7 g, Y# _7 z6 ^$ w2 |$ R2 ]" {
    package apitestimport  "fmt")test := "This is a test."func main()      fmt.Println(test)    test = "Another value"    fmt.Println(test)}
    0 t7 T6 B0 t6 P  ~7 m6 p5 X$ V# z
声明全局可访问变量,但不一定是常用 Go 的方法是什么?' c! H* q# X: X! E' l$ W
我的test变量需要:- b2 O: B) O  Q1 O4 t
可以访问自己包里的任何地方。+ ^# l8 r8 c8 h3 E
多变
                                                               
) V0 u5 V1 h1 D- u/ c    解决方案:                                                                ( v* |. N% \4 p6 |# c) F
                                                                你需要
+ L( V; k: k4 n0 R
    var test = "This is a test"# K8 f1 [2 Q: @6 y, N1 V
:= 只适用于函数,小写t只对包可见(未导出)。' K; {* P9 E# I% S" P& N
更彻底的解释
2 r/ o8 u1 R6 ^/ ?6 Q. |1 M8 htest1.go
7 D# p5 d6 a' k. k6 ?+ 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)}
    . l* w. s+ @/ V- _
test2.go1 ^& k" L: o6 Z, k3 z+ X
    package mainfunc changeTest(newTest string)    test = newTest}5 q+ g5 y  w& P# E2 I
输出
: J( }/ X6 U7 [) B5 Y
    testingSomething ElseType can be inferred$ K) I7 `* L# ?+ I
或者,对于更复杂的包初始化或设置包所需的任何状态,GO 提供了一个 init 函数。
+ f; e/ K( H7 z; z
    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]}
    , e5 O) m( ~- w8 C8 i* Z  h
init 将在 main 运行前调用。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则