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

时间:2015-07-30 14:17:45

标签: 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的所有路由。

有关如何找到此问题的简洁解决方法的任何想法?

2 个答案:

答案 0 :(得分:8)

稍后在init()内分配值。这将首先初始化GetRoutes函数,然后分配它。

type Routes []Route

var routes Routes

func init() {
    routes = Routes{
        Route{
            Name:        "GetRoutes",
            Method:      GET,
            Pattern:     "/routes",
            HandlerFunc: GetRoutes,
        },
    }
}

答案 1 :(得分:2)

使用init

var routes Routes

func init() {
    routes = Routes{
        Route{
            Name:        "GetRoutes",
            Method:      GET,
            Pattern:     "/routes",
            HandlerFunc: GetRoutes,
        },
    }
}