package main
import (
"fmt"
"reflect"
)
func main() {
mp := reflect.MakeMap(reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf("")))
//mp := reflect.MakeMapWithSize(reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf("")),10) // 创建的同时设置size
mp.SetMapIndex(reflect.ValueOf("hello"), reflect.ValueOf("hello")) // map["hello"] = "hello"
mp.SetMapIndex(reflect.ValueOf("world"), reflect.ValueOf("world"))
mp.SetMapIndex(reflect.ValueOf("2023"), reflect.ValueOf("2023"))
mp.SetMapIndex(reflect.ValueOf("加油"), reflect.ValueOf("加油"))
mp1 := reflect.MakeMap(reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf("")))
mp1.SetMapIndex(reflect.ValueOf("mp1"), reflect.ValueOf("mp1")) // map["hello"] = "hello"
it := mp.MapRange() // 迭代器
for it.Next() { // Next 判断是否有下一个值
k := reflect.New(mp.Type().Key()).Elem() // MapOf中的key类型
v := reflect.New(mp.Type().Elem()).Elem() // MapOf中的elem类型
k.SetIterKey(it) //将当前的key 赋值给k SetIterKey assigns to v the key of iter's current map entry. It is equivalent to v.Set(iter.Key()), but it avoids allocating a new Value. As in Go, the key must be assignable to v's type
v.SetIterValue(it) //将当前的value 赋值给v // SetIterValue assigns to v the value of iter's current map entry. It is equivalent to v.Set(iter.Value()), but it avoids allocating a new Value. As in Go, the value must be assignable to v's type.
fmt.Println("k", k.Interface().(string), "v", v.Interface().(string))
fmt.Println(it.Key(), ":", it.Key())
}
it.Reset(mp1) // 将迭代器绑定到其他map上,复用迭代器
for it.Next() {
fmt.Println("复用it", it.Key(), ":", it.Key())
}
return
fmt.Println(mp.MapKeys()) // map 的所有key
fmt.Println(mp.MapIndex(reflect.ValueOf("2023"))) // 等价于 map["2023"],即取值
fmt.Println(mp.Len()) // len(map)
//map 如何进行delete?
}
reflect 与 map
于 2022-11-25 12:28:16 首次发布