从数组创建结构体

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

Creating a struct from array

问题

我有一个Employee struct,它的结构如下:

  1. type Employee struct {
  2. firstName string
  3. lastName string
  4. role string
  5. }

我从一个Excel文件中读取了一行数据,这些数据的顺序与结构体中的字段对应。
我创建了一个数组来保存这些数据,所以数组的结构如下:

[personFirstName, personLastName, personRole]

我想用这些数据来初始化我的Employee结构体。
但是我不知道如何做,因为我不能像遍历数组那样遍历Employee结构体。
我考虑手动实现,像这样:

  1. e := Employee{
  2. firstName: array[0],
  3. lastName: array[1],
  4. role: array[2],
  5. }

但我觉得应该有更好的方法。
有什么想法吗?

英文:

I have an Employee struct which looks like this:

  1. type Employee struct {
  2. firstName string
  3. lastName string
  4. role string
  5. }

I read from an Excel file a row, which has the corresponding columns in the same order.
From the excel file I created an array that holds this data, so the array looks like this:

[personFirstName, personLastName, personRole]

And I want to initialize my Employee struct with it.
But I can't figure out how, because I can't iterate over the Employee struct like it's an array.
I thought about doing it manually, like this:

  1. e := {
  2. firstName: array[0],
  3. lastName: array[1],
  4. role: array[2],
  5. }

But I guess there should be a better way.
Any Ideas?

答案1

得分: 0

问题中的代码没有问题。以下是如何使用反射 API 实现目标的方法:

将字段导出,以便可以通过反射 API 设置字段的值。

  1. type Employee struct {
  2. FirstName string
  3. LastName string
  4. Role string
  5. }

创建一个员工的反射值。使用&Elem()来获取可设置的值。

  1. var e Employee
  2. v := reflect.ValueOf(&e).Elem()

对于每个字段,设置字符串值:

  1. for i := 0; i < v.NumField(); i++ {
  2. v.Field(i).SetString(values[i])
  3. }

Go Playground上运行示例。

如果需要在多个地方使用该代码,请将其放入一个函数中:

  1. // setStrings 将指针指向的结构体的字段设置为指定的值。
  2. func setStrings(ptr interface{}, values []string) {
  3. v := reflect.ValueOf(ptr).Elem()
  4. for i := 0; i < v.NumField(); i++ {
  5. v.Field(i).SetString(values[i])
  6. }
  7. }

像这样调用它:

  1. values := []string{"Monica", "Smith", "Manager"}
  2. var e Employee
  3. setStrings(&e, values)
  4. fmt.Printf("%+v\n", e) // 输出 {FirstName:Monica LastName:Smith Role:Manager}

playground上运行示例。

英文:

There's nothing wrong with the code in the question. Here's how to use the reflect API to accomplish the goal:

Export the field to make the fields settable through the reflect API.

  1. type Employee struct {
  2. FirstName string
  3. LastName string
  4. Role string
  5. }

Create reflect value for an employee. The &amp; and Elem()
shenanigans are required to get a settable value.

  1. var e Employee
  2. v := reflect.ValueOf(&amp;e).Elem()

For each field, set the string:

  1. for i := 0; i &lt; v.NumField(); i++ {
  2. v.Field(i).SetString(values[i])
  3. }

Run an example on the Go Playground.

Put the code in a function if you need it in more than one place:

  1. // setStrings sets the fields of the struct pointed
  2. // to by ptr to the specified values.
  3. func setStrings(ptr interface{}, values []string) {
  4. v := reflect.ValueOf(ptr).Elem()
  5. for i := 0; i &lt; v.NumField(); i++ {
  6. v.Field(i).SetString(values[i])
  7. }
  8. }

Call it like this:

  1. values := []string{&quot;Monica&quot;, &quot;Smith&quot;, &quot;Manager&quot;}
  2. var e Employee
  3. setStrings(&amp;e, values)
  4. fmt.Printf(&quot;%+v\n&quot;, e) // prints {FirstName:Monica LastName:Smith Role:Manager}

Run an example on the playground.

huangapple
  • 本文由 发表于 2021年6月29日 01:10:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/68167496.html
匿名

发表评论

匿名网友

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

确定