英文:
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 &
and Elem()
shenanigans are required to get a settable value.
var e Employee
v := reflect.ValueOf(&e).Elem()
For each field, set the string:
for i := 0; i < 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 < v.NumField(); i++ {
v.Field(i).SetString(values[i])
}
}
Call it like this:
values := []string{"Monica", "Smith", "Manager"}
var e Employee
setStrings(&e, values)
fmt.Printf("%+v\n", e) // prints {FirstName:Monica LastName:Smith Role:Manager}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论