douyue6520 2015-07-30 14:17
浏览 140
已采纳

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

When I try to compile this code:

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)
    }
}

<kbd>Playground</kbd>

the compiler returns this error message:

main.go:36: initialization loop:
    main.go:36 routes refers to
    main.go:38 GetRoutes refers to
    main.go:36 routes

The goal of this code is to return all the routes of my API in a JSON when a client application executes a GET request on the the /routes route.

Any idea on how can I find a clean workaround to this problem?

  • 写回答

2条回答 默认 最新

  • dongxianghuan3587 2015-07-30 14:21
    关注

    Assign the value later within init(). This will let the GetRoutes function be initialized first, then it can be assigned.

    type Routes []Route
    
    var routes Routes
    
    func init() {
        routes = Routes{
            Route{
                Name:        "GetRoutes",
                Method:      GET,
                Pattern:     "/routes",
                HandlerFunc: GetRoutes,
            },
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统