map - 遍历 golang 结构的键和值由于某种原因没有给出相同的结果

标签 map go

我有一个这样的 golang 映射:

var routes map[string]*rest.Route

我像这样向它添加了一堆键/值:

routes["Index"] = &rest.Route{"GET", "/", handlers.GetIndex}
routes["ListStudents"] = &rest.Route{"GET", "/students", handlers.ListStudents}
routes["ViewStudent"] = &rest.Route{"GET", "/students/:id", handlers.ViewStudent}
routes["CreateStudent"] = &rest.Route{"POST", "/students", handlers.CreateStudent}
routes["UpdateStudent"] = &rest.Route{"PUT", "/students/:id", handlers.UpdateStudent}
routes["DeleteStudent"] = &rest.Route{"DELETE", "/students/:id", handlers.DeleteStudent}

当我调用函数 SetRoute 时,它​​会像这样工作:

handler.SetRoutes(routes["Index"])

但是,当我尝试使用范围遍历 map 时,它不起作用。我知道它不起作用,因为之后会进行测试。但是,如果我在调用 SetRoute 时打印出键和值,我可以看到键和值是我所期望的。具体来说,这些值是地址。

// This doesn't work, even though printing out k,v shows nothing wrong...
for k, v := range routes {
    err := handler.SetRoutes(v)
    fmt.Println(k)
    fmt.Println(v)
    if err != nil {
        log.Fatal(err)
    }
}

打印出来显示:

Index
&{GET / 0x442250}
ListStudents
&{GET /students 0x4422f0}
ViewStudent
&{GET /students/:id 0x4427c0}
UpdateStudent
&{PUT /students/:id 0x443520}
DeleteStudent
&{DELETE /students/:id 0x443a30}
CreateSchool
&{POST /schools 0x444660}
CreateStudent
&{POST /students 0x442ed0}
ListSchools
&{GET /schools 0x443d50}
ViewSchool
&{GET /schools/:id 0x444200}
UpdateSchool
&{PUT /schools/:id 0x444cc0}
DeleteSchool
&{DELETE /schools/:id 0x4453b0}

我做错了什么?

最佳答案

handler.SetRoutes 似乎是可变的。您可以将多个路由传递给它。

这应该有效:

routes := []rest.Route{
  rest.Route{"GET", "/", handlers.GetIndex},
  rest.Route{"GET", "/students", handlers.ListStudents},
  // more routes
}
handler.SetRoutes(routes...)

关于map - 遍历 golang 结构的键和值由于某种原因没有给出相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23550851/

相关文章:

go - 是什么导致 'go build' 以 'unexpected NUL in input' 失败?

go - 在推断出 GOPATH 时运行(安装)go 代码

Go语言将模数指数转换为X.509证书

java - 按原始顺序打印结果

haskell - map haskell中的最小值

java数据结构模拟数据树

c++ - 在 SWIG 中包含 OpenCV core.hpp 时出现语法错误

algorithm - UTXO选择策略

functional-programming - Clojure:测试 map 操作中的每个值是否为真

map - Go 有迭代器数据类型吗?