如何在GO中创建通用数组?

问题描述 投票:0回答:1

我有一个函数需要接收 GORM 模型作为参数,并且根据我作为参数接收的模型,我需要根据我接收的结构(gorm 模型)的类型创建一个数组(切片)。如何创建我收到的模型类型的“记录”数组?

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 = ';'

        records := ??? //create array by model struct type

        if err := gocsv.UnmarshalCSVWithoutHeaders(reader, &records); err != nil {
            panic(err)
        }
        fmt.Printf("Creating records in database... ")
        db.CreateInBatches(records, 50)
        fmt.Println("Done")
    }
}
arrays go generics go-gorm
1个回答
0
投票

将指针作为参数传递给切片,而不是创建切片。

func processFiles(db *gorm.DB, contains string, records 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 = ';'

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

来电者看起来像这样:

var records []models.Empresa
processFiles(db, "EMPRE", &records)
© www.soinside.com 2019 - 2024. All rights reserved.