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

如何在Go中创建对应GORM模型类型的泛型切片?

解决方法:通过反射创建对应模型类型的切片

要根据传入的GORM模型结构体类型动态创建对应切片,可利用Go语言的reflect包实现,具体代码修改如下:

func main() {
    db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
    if err != nil {
        panic(err)
    }

    db.AutoMigrate(&models.Empresa{}, &models.Estabelecimento{})
    processFiles(db, "EMPRE", models.Empresa{})
    processFiles(db, "ESTABE", models.Estabelecimento{})
}

func processFiles(db *gorm.DB, contains string, model interface{}) {
    for _, fileName := range getCSVFiles(contains) {
        fmt.Println("Processing file", fileName)

        file, err := os.Open(filepath.Join(csvPath, fileName))
        if err != nil {
            panic(err)
        }
        defer file.Close()

        reader := csv.NewReader(file)
        reader.Comma = ';'

        // 动态生成对应模型类型的切片
        modelType := reflect.TypeOf(model)
        sliceType := reflect.SliceOf(modelType)
        records := reflect.MakeSlice(sliceType, 0, 0).Interface()

        if err := gocsv.UnmarshalCSVWithoutHeaders(reader, &records); err != nil {
            panic(err)
        }
        fmt.Printf("Creating records in database... ")
        db.CreateInBatches(records, 50)
        fmt.Println("Done")
    }
}

关键逻辑说明

  1. 获取模型类型:通过reflect.TypeOf(model)拿到传入结构体的类型信息
  2. 生成切片类型:用reflect.SliceOf(modelType)基于模型类型构建切片类型
  3. 实例化切片:reflect.MakeSlice创建切片实例,参数依次为切片类型、初始长度、初始容量,这里设初始长度和容量为0,后续由gocsv自动填充
  4. 转换为通用类型:通过.Interface()将反射对象转为interface{},赋值给records

如果需要优化性能,可以调整reflect.MakeSlice的第三个参数(初始容量),比如设为100,减少切片扩容带来的开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:57:10