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

ser*_*erg 50 variables scope global package go

我正在构建一个提供JSON或XML格式数据的API的Go库.

此API要求我session_id每15分钟左右请求一次,并在通话中使用它.例如:

foo.com/api/[my-application-id]/getuserprofilejson/[username]/[session-id]
foo.com/api/[my-application-id]/getuserprofilexml/[username]/[session-id]
Run Code Online (Sandbox Code Playgroud)

在我的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)

}
Run Code Online (Sandbox Code Playgroud)

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

我的test变量需要:

  • 可以从它自己的包装中的任何地方访问.
  • 变化多端

rob*_*bmj 69

你需要

var test = "This is a test"
Run Code Online (Sandbox Code Playgroud)

:= 仅适用于函数,小写't'仅适用于包(未导出).

更多的通过explenation

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)
}
Run Code Online (Sandbox Code Playgroud)

test2.go

package main

func changeTest(newTest string) {
    test = newTest
}
Run Code Online (Sandbox Code Playgroud)

产量

testing
Something Else
Type can be inferred
Run Code Online (Sandbox Code Playgroud)

或者,对于更复杂的包初始化或设置包所需的任何状态,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]
}
Run Code Online (Sandbox Code Playgroud)

在main运行之前将调用Init.


J.M*_*SON 18

如果你不小心使用" Func "或" function "或" Function "而不是" func ",你也会得到:

功能体外的非声明声明

发布这个是因为我最初在我的搜索中找到了什么是错的.


dan*_*ina 6

短变量声明:=,即只能函数内使用。

例如

func main() {
    test := "this is a test"
    // or
    age := 35
}
Run Code Online (Sandbox Code Playgroud)

var, func, const在函数外部的声明中,您必须根据您的需要使用诸如 etc 之类的关键字(在本例中我们使用的是var

在函数外部声明变量可以使其在其包内进行访问。

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)

}
Run Code Online (Sandbox Code Playgroud)

额外信息

如果您希望变量在其包内和包外都可访问,则该变量必须大写,例如

var Test string = "this is a test"
Run Code Online (Sandbox Code Playgroud)

这将使它可以从任何包访问。