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

当我尝试编译此代码时:


package main


import (

    "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 []Route


var 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 的所有路由。


关于如何找到解决此问题的干净方法的任何想法?


宝慕林4294392
浏览 144回答 2
2回答

慕斯709654

稍后在init(). 这将使GetRoutes函数首先被初始化,然后它可以被分配。type Routes []Routevar routes Routesfunc init() {    routes = Routes{        Route{            Name:        "GetRoutes",            Method:      GET,            Pattern:     "/routes",            HandlerFunc: GetRoutes,        },    }}

慕哥9229398

使用init:var routes Routesfunc init() {    routes = Routes{        Route{            Name:        "GetRoutes",            Method:      GET,            Pattern:     "/routes",            HandlerFunc: GetRoutes,        },    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go