英文:
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)
}
}
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: "GetRoutes",
Method: GET,
Pattern: "/routes",
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: "GetRoutes",
Method: GET,
Pattern: "/routes",
HandlerFunc: GetRoutes,
},
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论