Golang中如何向map添加值及在map中追加数组值

Golang中如何向map添加值及在map中追加数组值 我有一个用例,需要创建一个以下类型的新映射。我基本上想检查键值是否存在于映射中,如果存在,那么我想追加映射的数组并插入值。如果不存在,那么我想初始化数组并追加它。

我面临的问题是,我创建的映射是空的——如何向其中添加值,以便我的条件判断不会总是失败。我该如何解决这个问题?

供参考:我向这个函数传递一个如下所示的请求,我正在检查(映射中的)值:

请求: [{ “Category”: “TP”, “Name”: “Golang”, }]

type Example struct {
   Category       string `json:"category"`
   Name           string `json:"name"`
}

for i := range Example{
			dict := make(map[string][]Example)
			if count, ok := dict["Category"]; ok {
				fmt.Printf("Found %d\n", count)
			} else {
				fmt.Println("not found")
				fmt.Println(i)
			}
		}

更多关于Golang中如何向map添加值及在map中追加数组值的实战教程也可以访问 https://www.itying.com/category-94-b0.html

7 回复

你能解释一下你所说的“动态”是什么意思吗?能展示更多例子来说明吗?

更多关于Golang中如何向map添加值及在map中追加数组值的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我不太明白,但这有帮助吗?https://play.golang.org/p/YqB65f3gkla

  • 确实如此。但请求将始终采用以下格式:
[{
	"Category": "Fun",
        "LastName":"Test"
	"Name": "Golang",
	
}]

因此,如果请求中存在 LastName 键值对,映射数组中的条目将如下所示:

 {
 {
	"Test": [
    {
      "Category": "Fun",
        "LastName":"Test"
	"Name": "Golang",
}
]
}

@skillian - 我正在从前端传递请求体,这是一个后端端点。因此,从前端发来的请求将是一个类似下面的JSON。所以在我的情况下,我需要检查请求中是否存在Category键,如果存在,我想将该值追加到数组中(就像你的示例一样)。如果该键无效,那么我想初始化一个数组,然后再追加它。

Frontend request JSON:
[{
“Category”: “TP”,
"LastName":"Test",
“Name”: “Golang”,
}]

大家好, 我有一个使用场景,需要创建一个以下类型的新映射。我基本上想检查键值是否存在于映射中,如果存在,那么我想追加映射的数组并插入值。如果不存在,那么我想初始化数组并追加它。 我面临的问题是,我创建的映射是空的——如何向其中添加值,以便我的条件判断不会总是失败。我该如何解决这个问题? 供参考:我传递了一个请求

@skillian - 感谢您的回复。是的,情况类似,但如果需要动态注入值,而不是像您的示例中那样将其声明为常量,我们该如何操作?请求来自前端,这是后端端点。

[{
	"Category": "TP",
	"Name": "Golang"
}]

那么,如果请求是:

[
  {
    "A": "abc",
    "B": "def"
  },
  {
    "A": "ghi",
    "C": "jkl"
  },
  {
    "A": "abc"
  }
]

结果应该是:

{
  "A": [
    {
      "A": "abc",
      "B": "def"
    },
    {
      "A": "ghi",
      "C": "jkl",
    },
    {
      "A": "abc"
    }
  ],
  "B": [
    {
      "A": "abc",
      "B": "def"
    }
  ],
  "C": [
    {
      "A": "ghi",
      "C": "jkl"
    }
  ]
}

首先,你的代码中存在几个问题。让我先修正你的代码,然后给出一个完整的示例。

主要问题:

  1. 你在循环中每次都重新创建 dict 映射
  2. 你检查的是 dict["Category"] 而不是具体的分类值
  3. 你的结构体字段标签与JSON字段不匹配

以下是修正后的代码:

package main

import (
	"encoding/json"
	"fmt"
)

type Example struct {
	Category string `json:"Category"`
	Name     string `json:"Name"`
}

func main() {
	// 示例JSON数据
	jsonData := `[{"Category": "TP", "Name": "Golang"}, {"Category": "TP", "Name": "Concurrency"}, {"Category": "DB", "Name": "PostgreSQL"}]`
	
	var examples []Example
	if err := json.Unmarshal([]byte(jsonData), &examples); err != nil {
		panic(err)
	}
	
	// 创建映射,键为分类,值为Example切片
	dict := make(map[string][]Example)
	
	for _, example := range examples {
		// 检查分类是否已存在于映射中
		if existing, ok := dict[example.Category]; ok {
			// 如果存在,追加到现有切片
			dict[example.Category] = append(existing, example)
			fmt.Printf("追加到分类 '%s': %s\n", example.Category, example.Name)
		} else {
			// 如果不存在,创建新切片
			dict[example.Category] = []Example{example}
			fmt.Printf("创建新分类 '%s': %s\n", example.Category, example.Name)
		}
	}
	
	// 打印结果
	fmt.Println("\n最终映射内容:")
	for category, items := range dict {
		fmt.Printf("分类: %s\n", category)
		for _, item := range items {
			fmt.Printf("  - %s\n", item.Name)
		}
	}
	
	// 访问特定分类
	fmt.Println("\n访问TP分类:")
	if tpItems, ok := dict["TP"]; ok {
		for _, item := range tpItems {
			fmt.Printf("  - %s\n", item.Name)
		}
	}
}

如果你想要一个更通用的函数来处理这种需求:

func addToCategoryMap(dict map[string][]Example, example Example) map[string][]Example {
	if dict == nil {
		dict = make(map[string][]Example)
	}
	
	if existing, ok := dict[example.Category]; ok {
		dict[example.Category] = append(existing, example)
	} else {
		dict[example.Category] = []Example{example}
	}
	
	return dict
}

// 使用示例
func main() {
	dict := make(map[string][]Example)
	
	// 添加示例数据
	dict = addToCategoryMap(dict, Example{Category: "TP", Name: "Golang"})
	dict = addToCategoryMap(dict, Example{Category: "TP", Name: "Concurrency"})
	dict = addToCategoryMap(dict, Example{Category: "DB", Name: "PostgreSQL"})
	
	fmt.Println("映射内容:", dict)
}

对于你的原始代码,关键修正点是:

  1. 在循环外部创建映射
  2. 使用 example.Category 作为键而不是硬编码的 "Category"
  3. 正确使用结构体字段标签来匹配JSON数据
回到顶部