【问题标题】:How to avoid initialization loop in Go如何避免 Go 中的初始化循环
【发布时间】:2015-07-30 14:17:45
【问题描述】:

当我尝试编译这段代码时:

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

Playground

编译器返回此错误消息:

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 的所有路由。

关于如何找到解决此问题的干净解决方法的任何想法?

【问题讨论】:

    标签: go


    【解决方案1】:

    稍后在init() 中分配值。这会让GetRoutes函数先被初始化,然后才能赋值。

    type Routes []Route
    
    var routes Routes
    
    func init() {
        routes = Routes{
            Route{
                Name:        "GetRoutes",
                Method:      GET,
                Pattern:     "/routes",
                HandlerFunc: GetRoutes,
            },
        }
    }
    

    【讨论】:

      【解决方案2】:

      使用init:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-21
        • 1970-01-01
        • 1970-01-01
        • 2018-02-17
        • 2015-12-23
        • 2011-03-14
        • 1970-01-01
        相关资源
        最近更新 更多