英文:
go: map of pointers or bools as map of interface
问题
假设我有不同类型的地图,其中包括布尔类型和指针类型,并且想要将它们以一种统一的方式传递给某个函数:
type Blah struct {
name string
}
var mapBlah map[string]*Blah = make(map[string]*Blah)
var mapBool map[string]bool = make(map[string]bool)
func joinKeys(m map[string]interface{}) string {
// 返回字符串.Join(map的键)
}
我似乎无法将这些地图传递给这个函数(示例)。如果我漏掉了什么,应该如何正确地完成这个操作,或者为什么不能完成呢?
英文:
Suppose I have maps of different types, among them of bools and of pointers and want to pass them to some function in single way:
type Blah struct {
name string
}
var mapBlah map[string]*Blah = make(map[string]*Blah)
var mapBool map[string]bool = make(map[string]bool)
func joinKeys(m map[string]interface{}) string {
// returns strings.Join(keys of map)
}
I seemingly can't pass these maps into this function (example). How can this be done properly, or
why it can't be done if I'm missing something, please?
答案1
得分: 1
当你已经知道类型时,我认为像下面这样切换类型会很有益处。
package main
import (
"fmt"
"strings"
)
type Blah struct {
name string
}
var mapBlah map[string]*Blah = make(map[string]*Blah)
var mapBool map[string]bool = make(map[string]bool)
func joinKeys(m interface{}) string {
var a []string
switch v := m.(type) {
case map[string]*Blah:
for k, _ := range v {
a = append(a, k)
}
case map[string]bool:
for k, _ := range v {
a = append(a, k)
}
default:
}
return strings.Join(a, ",")
}
func main() {
mapBlah["1B"] = &Blah{name: "first"}
mapBlah["2B"] = &Blah{name: "second"}
fmt.Println(joinKeys(mapBlah))
mapBool["1Bool"] = true
fmt.Println(joinKeys(mapBool))
}
对于更具动态性但性能有所牺牲的方式,可以使用reflection
。
英文:
When you already know the types, I think switching over types will be beneficial like follows.
package main
import (
"fmt"
"strings"
)
type Blah struct {
name string
}
var mapBlah map[string]*Blah = make(map[string]*Blah)
var mapBool map[string]bool = make(map[string]bool)
func joinKeys(m interface{}) string {
var a []string
switch v := m.(type) {
case map[string]*Blah:
for k, _ := range v {
a = append(a, k)
}
case map[string]bool:
for k, _ := range v {
a = append(a, k)
}
default:
}
return strings.Join(a, ",")
}
func main() {
mapBlah["1B"] = &Blah{name: "first"}
mapBlah["2B"] = &Blah{name: "second"}
fmt.Println(joinKeys(mapBlah))
mapBool["1Bool"] = true
fmt.Println(joinKeys(mapBool))
}
For more dynamic way with some performance tradeoffs reflection
is way to go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论