从数组创建结构体

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

Creating a struct from array

问题

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

type Employee struct {
  firstName string
  lastName  string
  role      string
}

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

[personFirstName, personLastName, personRole]

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

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

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

英文:

I have an Employee struct which looks like this:

type Employee struct {
  firstName string
  lastName  string
  role      string
}

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:

e := {
  firstName: array[0],
  lastName: array[1],
  role: array[2],
}

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

答案1

得分: 0

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

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

type Employee struct {
    FirstName string
    LastName  string
    Role      string
}

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

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

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

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

Go Playground上运行示例。

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

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

像这样调用它:

values := []string{"Monica", "Smith", "Manager"}
var e Employee
setStrings(&e, values)
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.

type Employee struct {
	FirstName string
	LastName  string
	Role      string
}

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

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

For each field, set the string:

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

Run an example on the Go Playground.

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

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

Call it like this:

values := []string{&quot;Monica&quot;, &quot;Smith&quot;, &quot;Manager&quot;}
var e Employee
setStrings(&amp;e, values)
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:

确定