为了账号安全,请及时绑定邮箱和手机立即绑定

如何避免 Go 中的初始化循环

如何避免 Go 中的初始化循环

Go
宝慕林4294392 2021-10-25 18:24:06
当我尝试编译此代码时:package mainimport (    "encoding/json"    "fmt"    "net/http")func main() {    fmt.Println("Hello, playground")}const (    GET    = "GET"    POST   = "POST"    PUT    = "PUT"    DELETE = "DELETE")type Route struct {    Name        string           `json:"name"`    Method      string           `json:"method"`    Pattern     string           `json:"pattern"`    HandlerFunc http.HandlerFunc `json:"-"`}type Routes []Routevar routes = Routes{    Route{        Name:        "GetRoutes",        Method:      GET,        Pattern:     "/routes",        HandlerFunc: GetRoutes,    },}func GetRoutes(res http.ResponseWriter, req *http.Request) {    if err := json.NewEncoder(res).Encode(routes); err != nil {        panic(err)    }}Playground编译器返回此错误消息:main.go:36: initialization loop:    main.go:36 routes refers to    main.go:38 GetRoutes refers to    main.go:36 routes此代码的目标是当客户端应用程序对/routes路由执行 GET 请求时,以 JSON 形式返回我的 API 的所有路由。关于如何找到解决此问题的干净方法的任何想法?
查看完整描述

2 回答

?
慕斯709654

TA贡献1840条经验 获得超5个赞

稍后在init(). 这将使GetRoutes函数首先被初始化,然后它可以被分配。


type Routes []Route


var routes Routes


func init() {

    routes = Routes{

        Route{

            Name:        "GetRoutes",

            Method:      GET,

            Pattern:     "/routes",

            HandlerFunc: GetRoutes,

        },

    }

}


查看完整回答
反对 回复 2021-10-25
?
慕哥9229398

TA贡献1877条经验 获得超6个赞

使用init:


var routes Routes


func init() {

    routes = Routes{

        Route{

            Name:        "GetRoutes",

            Method:      GET,

            Pattern:     "/routes",

            HandlerFunc: GetRoutes,

        },

    }

}


查看完整回答
反对 回复 2021-10-25
  • 2 回答
  • 0 关注
  • 143 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信