简体   繁体   English

以Maps Go语言转换VALUES的数据类型

[英]Convert the dataype of VALUES in Maps Go language

I have a map in GO as : 我在GO中的地图为:

var userinputmap = make(map[string]string)

and the values in it are of type : 并且其中的值是类型:

[ABCD:30 EFGH:50 PORS:60]

Not that the 30,50,60 are strings over here. 并不是说30,50,60是这里的字符串。

I wish to have a same map but the numeric values should have float64 type instead of string type. 我希望有一个相同的映射,但数值应具有float64类型而不是字符串类型。

Desired output : 所需输出:

var output = make(map[string]float64)

I tried to do it but I get an error : cannot use <placeholder_name> (type string) as type float64 in assignment 我尝试这样做,但出现错误: cannot use <placeholder_name> (type string) as type float64 in assignment

You cannot do this by simple typecasting; 您不能通过简单的类型转换来做到这一点; the two maps have different representations in memory. 这两个映射在内存中具有不同的表示形式。

To solve this, you will have to iterate over every entry of the first map, convert the string representation of the float to a float64 , then store the new value in the other map: 为了解决这个问题,您将必须遍历第一个映射的每个条目,将float的字符串表示形式转换为float64 ,然后将新值存储在另一个映射中:

import "strconv"

var output = make(map[string]float64)
for key, value := range userinputmap {
    if converted, err := strconv.ParseFloat(value, 64); err == nil {
        output[key] = converted
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM