如何避免Go中的初始化循环
当我尝试编译此代码时:如何避免Go中的初始化循环,go,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 {
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)
}
}
编译器返回此错误消息:
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的所有路由
你知道我该如何找到解决这个问题的方法吗 使用:
稍后在
init()
中指定值。这将首先初始化GetRoutes
函数,然后才能分配它
type Routes []Route
var routes Routes
func init() {
routes = Routes{
Route{
Name: "GetRoutes",
Method: GET,
Pattern: "/routes",
HandlerFunc: GetRoutes,
},
}
}
type Routes []Route
var routes Routes
func init() {
routes = Routes{
Route{
Name: "GetRoutes",
Method: GET,
Pattern: "/routes",
HandlerFunc: GetRoutes,
},
}
}