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()函数之外创建一个变量,并打算为每个API调用ping它一个值。如果该值为零或为空,则请求一个新的会话id,依此类推

package apitest
import (
    "fmt"
)
test := "This is a test."
func main() {
    fmt.Println(test)
    test = "Another value"
    fmt.Println(test)
}

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

我的test变量需要:

  • 可以从自己的包中的任何地方访问
  • 多变

您需要

var test = "This is a test"

:=仅适用于函数,小写字母"t"仅对包可见(未导出)。

更全面的解释

测试1.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)
}

测试2.go

package main
func changeTest(newTest string) {
    test = newTest
}

输出

testing
Something Else
Type can be inferred

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

Init将在main运行之前调用。

如果您不小心使用"Func"或"函数"或"功能

函数体之外的非声明语句

发布这篇文章是因为我最初在这里搜索是为了找出问题所在。

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

例如

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

函数外的声明必须使用var, func, const e.t.c等关键字,这取决于您想要的(在本例中,我们使用的是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)
}

额外信息

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

var Test string = "this is a test"

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

我们可以如下声明变量:

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
}

在函数之外,每条语句都以关键字(varfunc等)开头,因此:=构造不可用。

您可以在此处阅读更多信息:https://tour.golang.org/basics/10

我在运行Go应用程序时遇到了这个错误,函数定义如下:

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

定义函数(接收器函数)的正确方法是:

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

最新更新