简体   繁体   中英

Convert the dataype of VALUES in Maps Go language

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 <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:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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