将指针或布尔值的映射转换为接口的映射。

huangapple go评论86阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年8月7日 15:27:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/68690253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定