设计思路
- 使用Go语言来实现,因为Go语言对接口和类型系统的支持有助于解决类型安全问题。
- 定义一个基础的结构体作为嵌套数据结构的节点,结构体中包含一个空接口字段来存储不同类型的数据。
- 使用
map[string]interface{}
来实现多层嵌套的map结构。
- 在添加新数据的函数中,使用类型断言和类型判断来确保类型安全。
代码实现
package main
import (
"fmt"
)
// 定义嵌套数据结构节点
type Node struct {
Data interface{}
}
// 添加新数据的函数
func AddData(nestedMap map[string]interface{}, keys []string, value interface{}) error {
current := nestedMap
for i, key := range keys {
if i == len(keys)-1 {
// 最后一个键,直接赋值
if _, ok := current[key]; ok {
return fmt.Errorf("key %s already exists", key)
}
current[key] = value
return nil
}
subMap, ok := current[key].(map[string]interface{})
if!ok {
newSubMap := make(map[string]interface{})
current[key] = newSubMap
current = newSubMap
} else {
current = subMap
}
}
return nil
}
func main() {
nestedMap := make(map[string]interface{})
keys := []string{"parent", "child", "grandchild"}
value := "new data"
err := AddData(nestedMap, keys, value)
if err != nil {
fmt.Println(err)
} else {
fmt.Println("Data added successfully:", nestedMap)
}
}