如何避免Go中的初始化循环 [英] How to avoid initialization loop in Go

查看:57
本文介绍了如何避免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)
    }
}

游乐场

编译器返回以下错误消息:

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

此代码的目标是当客户端应用程序在/routes 路由上执行GET请求时,以JSON返回我的API的所有路由.

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?

推荐答案

稍后在 init()中分配值.这样将首先初始化 GetRoutes 函数,然后可以对其进行分配.

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

这篇关于如何避免Go中的初始化循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆