使用Golang数组和forEach方法填充模型。

huangapple go评论88阅读模式
英文:

Golang array with forEach to fill model

问题

我有一个动态导入,人们可以选择用于特定行的字段。在Golang中,我显然会收到这个数组,并希望循环遍历导入的CSV,并将每一行添加到模型的特定部分。请参见我当前的代码。

applicant := models.Applicant{
    Prefix:    "",
    FirstName: "",
    LastName:  "",
    Email:     "",
    Telephone: "",
    Mobile:    "",
    Gender:    "",
    CreatedAt: time.Time{},
    UpdatedAt: nil,
    DeletedAt: nil,
}

row := 0
splitted := strings.Split(details[0], ",")
data := strings.Split(rec[0], ";")

for i := range splitted {
    if splitted[i] != "" {    
        applicant[splitted[i]] = data[row]
    }

    row++
}

显然,这样做是行不通的,因为我不能在我的for循环中写:

applicant[splitted[i]] = data[row]

因为模型不支持索引。我已经搜索了几个小时,但无法找到解决我的问题的方法。

请问有人可以帮助我并告诉我如何使这个工作起来吗?

英文:

I have a dynamic import where people can choose what field to use for a specific row.
In Golang, I receive this array obviously and want to loop through the imported CSV and add each row to a specific part of the model. See my current code below.

applicant := models.Applicant{
	Prefix:                        "",
	FirstName:                     "",
	LastName:                      "",
	Email:                         "",
	Telephone:                     "",
	Mobile:                        "",
	Gender:                        "",
	CreatedAt:                     time.Time{},
	UpdatedAt:                     nil,
	DeletedAt:                     nil,
}

row := 0
splitted := strings.Split(details[0], ",")
data := strings.Split(rec[0], ";")

for i := range splitted {
	if splitted[i] != "" {    
		applicant[splitted[i]] = data[row]
	}

	row++
}

Obviously this won't work because I cannot say (in my for loop):

applicant[splitted[i]] = data[row]

Because a model does not support indexing. I have been Googling for hours but I am unable to find a solution to my problem.

Can anyone please help me out and tell me how I can make this work?

答案1

得分: 0

如果该模型是一个任意结构,你可能需要使用反射来修改其中一个字段。

例如,可以参考这个答案,它添加了一个SetStringField2()方法,使用Value.SetString()调用来修改字段的(字符串)值。

示例代码如下:

a := struct {
    Name string
}{}

// 可行的操作
reflect.ValueOf(&a).Elem().FieldByName("Name").SetString("Hello")
fmt.Printf("%#v\n", a)
英文:

If that model is an arbitrary structure, you might need to use reflection on order to modify one of its fields.

See for instance this answer, which adds a SetStringField2() method, using a Value.SetString() call to modify the (string) value of a field.

Example:

	a := struct {
		Name string
	}{}

	// works
	reflect.ValueOf(&a).Elem().FieldByName("Name").SetString("Hello")
	fmt.Printf("%#v\n", a)

huangapple
  • 本文由 发表于 2022年5月28日 16:36:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/72414148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定