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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?