英文:
Casting map types
问题
我正在尝试编写一个通用函数来获取映射的键,代码如下:
func MapKeys(theMap map[interface{}]interface{}) ([]interface{}, error) {
if theMap == nil {
return nil, errors.New("MapKeys arg is nil")
}
var keys = make([]interface{}, len(theMap), len(theMap))
i := 0
for idx, _ := range theMap {
keys[i] = idx
i++
}
return keys, nil
}
A) 有没有更好的方法来实现这个功能?B) 在调用这个函数时,如何将原始的映射类型转换为map[interface{}]interface{}
类型?
英文:
I'm trying to write a general function to get the keys of a map like so:
func MapKeys(theMap map[interface{}]interface{}) ([]interface{},error) {
if theMap == nil {
return nil,errors.New("MapKeys arg is nil")
}
var keys = make([]interface{}, len(theMap), len(theMap))
i := 0
for idx,_ := range theMap {
keys[i] = idx
i++
}
return keys, nil
}
A) Is there a better way to do this? and B) When calling this function, how do I cast the original map types to map[interface{}]interface{}?
答案1
得分: 1
你无法将现有的 map 转换为 map[interface{}]interface{}
。你需要使用反射来实现:
func MapKeys(theMap interface{}) ([]interface{}, error) {
if theMap == nil {
return nil, errors.New("MapKeys arg is nil")
}
v := reflect.ValueOf(theMap) // v 现在是 reflect.Value 类型
if v.Kind() != reflect.Map {
return nil, errors.New("Argument is not a map")
}
var keys = make([]interface{}, v.Len(), v.Len())
for i, key := range v.MapKeys() {
keys[i] = key.Interface() // key 也是 reflect.Value,key.Interface() 将其转换回 interface
}
return keys, nil
}
工作示例:https://play.golang.org/p/h9ZfnLHXgX
英文:
You cannot cast an existing map into a map[interface{}]interface{}
. You'll have to make use of reflection:
func MapKeys(theMap interface{}) ([]interface{}, error) {
if theMap == nil {
return nil,errors.New("MapKeys arg is nil")
}
v := reflect.ValueOf(theMap) // v is now a reflect.Value type
if v.Kind() != reflect.Map {
return nil, errors.New("Argument is not a map")
}
var keys = make([]interface{}, v.Len(), v.Len())
for i, key := range v.MapKeys() {
keys[i] = key.Interface() // key is also a reflect.Value, key.Interface()
// converts it back into an interface
}
return keys, nil
}
Working example: https://play.golang.org/p/h9ZfnLHXgX
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论