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

如何用Go泛型实现单个函数遍历切片或映射?

借助Go泛型实现同时遍历切片和map的函数

你的代码报错是因为[]interface{}和map[string]interface{}没有共同的核心类型,编译器无法确定range items的返回值类型,因此直接对联合类型的类型参数执行range操作是不允许的。

要实现支持遍历两种类型的函数,需要在函数内部通过类型断言区分具体类型,分别处理切片和map的遍历逻辑。示例代码如下:

package main

import "fmt"

func iterateContent[K []interface{} | map[string]interface{}](items K) {
    switch val := any(items).(type) {
    case []interface{}:
        for idx := range val {
            fmt.Println(idx)
            // 在这里添加切片相关的业务逻辑
        }
    case map[string]interface{}:
        for key := range val {
            fmt.Println(key)
            // 在这里添加map相关的业务逻辑
        }
    }
}

func main() {
    testSlice := []interface{}{100, "hello", false}
    iterateContent(testSlice)

    testMap := map[string]interface{}{"name": "Alice", "age": 25}
    iterateContent(testMap)
}

补充说明

  • 切片遍历返回的idx是int类型的索引,map遍历返回的key是string类型的键,两者的语义和类型都不同,因此无法用单个for循环统一处理,必须分开分支实现。
  • 如果需要更清晰的约束定义,可以自定义一个接口类型:
    type Iterable interface {
        []interface{} | map[string]interface{}
    }
    
    func iterateContent[K Iterable](items K) {
        // 内部逻辑同上
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:36:13