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

我正在为提供 JSON 或 XML 格式数据的 API 构建 Go 库。

这个 API 要求我每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() func 之外创建一个变量,并打算为每个 API 调用 ping 它的值。如果该值为 nil 或空,则请求一个新的会话 ID,以此类推。

package apitest


import (
"fmt"
)


test := "This is a test."


func main() {
fmt.Println(test)
test = "Another value"
fmt.Println(test)


}

声明一个全局可访问的变量,但不一定是一个常量的惯用 Go 方法是什么?

我的 test变量需要:

  • 可以从它自己的包中的任何地方访问。
  • 变化无常
88495 次浏览

You need

var test = "This is a test"

:= only works in functions and the lower case 't' is so that it is only visible to the package (unexported).

A more thorough explanation

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
}

output

testing
Something Else
Type can be inferred

Alternatively, for more complex package initializations or to set up whatever state is required by the package GO provides an init function.

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]
}

Init will be called before main is run.

If you accidentally use "Func" or "function" or "Function" instead of "func" you will also get:

non-declaration statement outside of function body

Posting this because I initially ended up here on my search to figure out what was wrong.

We can declare variables as below:

package main


import (
"fmt"
"time"
)


var test = "testing"
var currtime = "15:04:05"
var date = "02/01/2006"


func main() {
t := time.Now()
date := t.Format("02/01/2006")
currtime := t.Format("15:04:05")


fmt.Println(test) //Output: testing
fmt.Println(currtime)//Output: 16:44:53
fmt.Println(date) // Output: 29/08/2018
}

Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.

You can read more information here: https://tour.golang.org/basics/10

Short variable declarations i.e. :=, can ONLY be used within functions.

e.g.

func main() {
test := "this is a test"
// or
age := 35
}

Declarations outside a function you must make use of keywords like var, func, const e.t.c depending on what you want (in this case we're using var).

Declaring a variable outside a function makes it accessible within its package.

package apitest


import (
"fmt"
)
// note the value can be changed
var test string = "this is a test"


func main() {
fmt.Println(test)
test = "Another value"
fmt.Println(test)


}

Extra info

If you want the variable to be accessible both within and outside its package, the variable has to be capitalized e.g.

var Test string = "this is a test"

this will make it accessible from any package.

I got this error when I was trying to run Go app with function definition like this:

(u *UserService) func GetAllUsers() (string, error) {...} //Error code

The correct way of defining a function (receiver function) was:

func (u *UserService) GetAllUsers() (string, error) {...} //Working code