gpt4 book ai didi

dictionary - 映射动态值类型?

转载 作者:IT王子 更新时间:2023-10-29 01:34:37 25 4
gpt4 key购买 nike

有什么方法可以创建具有动态值类型的映射,以在单个映射中同时存储浮点值和字符串值?

myMap["key"] = 0.25
myMap["key2"] = "some string"

最佳答案

您可以使用 interface{} 作为映射的值,它将存储您传递的任何类型的值,然后使用类型断言获取基础值。

package main

import (
"fmt"
)

func main() {
myMap := make(map[string]interface{})
myMap["key"] = 0.25
myMap["key2"] = "some string"
fmt.Printf("%+v\n", 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")
}
}
}

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

如果您不使用 switch 类型来获取值:

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

您可以在 switch case 中添加任意数量的类型来获取值

关于dictionary - 映射动态值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52454489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com