You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Go语言中获取slice A中不存在于slice B的元素

你需要得到的是 slice A 与 B 的差集(即所有存在于A但不存在于B中的元素)。你当前代码的逻辑刚好相反,是把两个slice的交集元素存入了temp,调整判断逻辑即可实现需求。

方案1:修改原有双层循环逻辑

适合B数据量较小的场景,逻辑简单直观:

package main

import "fmt"

func main() {
	A := []string{"a", "b", "c", "d"}
	B := []string{"a", "b"}
	res := []string{}

	for _, a := range A {
		existInB := false
		for _, b := range B {
			if a == b {
				existInB = true
				break
			}
		}
		// 仅保留不存在于B中的元素
		if !existInB {
			res = append(res, a)
		}
	}
	fmt.Println(res) // 输出:[c d]
}

方案2:基于Map实现(推荐大数据量场景)

如果B的元素数量较多,双层循环的O(n*m)时间复杂度会很高,把B转成Map做存在性校验可以把整体时间复杂度降到O(n+m):

package main

import "fmt"

func main() {
	A := []string{"a", "b", "c", "d"}
	B := []string{"a", "b"}
	res := []string{}

	// 先把B的元素存入Map做标记
	bMap := make(map[string]struct{}, len(B))
	for _, b := range B {
		bMap[b] = struct{}{} // 空结构体不占用内存,仅做存在性标识
	}

	// 遍历A筛选不在Map中的元素
	for _, a := range A {
		if _, ok := bMap[a]; !ok {
			res = append(res, a)
		}
	}
	fmt.Println(res) // 输出:[c d]
}

内容的提问来源于stack exchange,提问作者dwlpra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 09:54:03