Is there any way to create a map with a dynamic value type, to store in a single map both float and string values?
myMap["key"] = 0.25
myMap["key2"] = "some string"
Is there any way to create a map with a dynamic value type, to store in a single map both float and string values?
myMap["key"] = 0.25
myMap["key2"] = "some string"
You can use interface{}
as the value for the map which will store any type of value you pass and then use type assertion to fetch the underlying value.
package main
import (
"fmt"
)
func main() {
myMap := make(map[string]interface{})
myMap["key"] = 0.25
myMap["key2"] = "some string"
fmt.Printf("%+v
", myMap)
// fetch value using type assertion
fmt.Println(myMap["key"].(float64))
fetchValue(myMap)
}
func fetchValue(myMap map[string]interface{}){
for _, value := range myMap{
switch v := value.(type) {
case string:
fmt.Println("the value is string =", value.(string))
case float64:
fmt.Println("the value is float64 =", value.(float64))
case interface{}:
fmt.Println(v)
default:
fmt.Println("unknown")
}
}
}
Working code on Playground
Variables of interface type also have a distinct dynamic type, which is the concrete type of the value assigned to the variable at run time (unless the value is the predeclared identifier nil, which has no type). The dynamic type may vary during execution but values stored in interface variables are always assignable to the static type of the variable.
var x interface{} // x is nil and has static type interface{}
var v *T // v has value nil, static type *T
x = 42 // x has value 42 and dynamic type int
x = v // x has value (*T)(nil) and dynamic type *T
If you do not the type use switch to fetch the value as:
func question(anything interface{}) {
switch v := anything.(type) {
case string:
fmt.Println(v)
case int32, int64:
fmt.Println(v)
case SomeCustomType:
fmt.Println(v)
default:
fmt.Println("unknown")
}
}
you can add as many types you want in the switch case to get the value