我正在提供 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