在Maps Go语言中,将VALUES的数据类型转换为:

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

Convert the dataype of VALUES in Maps Go language

问题

我有一个GO语言的地图,如下所示:

var userinputmap = make(map[string]string)

其中的值的类型为:

[ABCD:30 EFGH:50 PORS:60]

请注意,这里的30、50、60是字符串。

我希望有一个相同的地图,但是数值类型应该是float64而不是字符串类型。

期望的输出是:

var output = make(map[string]float64)

我尝试过,但是出现了错误:cannot use <placeholder_name> (type string) as type float64 in assignment

英文:

I have a map in GO as :

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.

I wish to have a same map but the numeric values should have float64 type instead of string type.

Desired output :

var output = make(map[string]float64)

I tried to do it but I get an error : cannot use &lt;placeholder_name&gt; (type string) as type float64 in assignment

答案1

得分: 2

你不能通过简单的类型转换来实现这个,这两个映射在内存中有不同的表示方式。

为了解决这个问题,你需要遍历第一个映射的每个条目,将浮点数的字符串表示转换为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
    }
}
英文:

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:

import &quot;strconv&quot;

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

huangapple
  • 本文由 发表于 2015年9月30日 09:04:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/32856154.html
匿名

发表评论

匿名网友

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

确定