转换地图类型

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

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

huangapple
  • 本文由 发表于 2016年7月21日 01:19:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/38486910.html
匿名

发表评论

匿名网友

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

确定