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

huangapple go评论73阅读模式
英文:

How to avoid initialization loop in Go

问题

当我尝试编译这段代码时,编译器返回以下错误信息:

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

这段代码的目标是在客户端应用程序执行对/routes路由的GET请求时,返回我的API的所有路由的JSON。你有什么办法可以找到一个干净的解决方法来解决这个问题吗?

英文:

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?

答案1

得分: 12

init()函数中稍后分配值。这将使GetRoutes函数首先初始化,然后可以进行分配。

type Routes []Route

var routes Routes

func init() {
    routes = Routes{
        Route{
            Name:        "GetRoutes",
            Method:      GET,
            Pattern:     "/routes",
            HandlerFunc: 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:        &quot;GetRoutes&quot;,
			Method:      GET,
			Pattern:     &quot;/routes&quot;,
			HandlerFunc: GetRoutes,
		},
	}
}

答案2

得分: 2

使用init

var routes Routes

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

Use init:

var routes Routes

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

huangapple
  • 本文由 发表于 2015年7月30日 22:17:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/31726254.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定