使用反映设置结构的结构的值的值
我有一些代码,看起来是工作,但什么都不做到底:使用反映设置结构的结构的值的值
http://play.golang.org/p/TfAWWy4-R8
有一个具有结构类型的字段的结构。内部结构包含所有字符串字段。
在循环中使用反射,希望从外部结构中获取所有结构字段。接下来,填充内部结构中的所有字符串值。示例代码从标签获取文本并在“,”解析它以获取内部循环的字符串值。
这是应该创建内部结构并将解析的数据添加到字符串值的主要部分。
t := reflect.TypeOf(Alias{})
alias = reflect.New(t)
for i := 0; i < alias.Elem().NumField(); i++ {
p := alias.Elem().Field(i)
p.SetString(params[i])
}
它看起来就像当你从例子中,输出工作,但打印从外部结构的值后,它似乎是空的:
fmt.Println("Final01 = ", Attr.Final01.Command) // prints empty string
所以不知道如何获取值进入内部结构Alias {}
感谢您的任何帮助。
Here的工作程序。下面的解释。
package main
import "fmt"
import "strings"
import "reflect"
type Alias struct {
Name string
DevicePath string
GuiPath string
Setpoint string
Command string
Status string
FunctionCmds string
}
type Manifold struct {
Final01 Alias "Final01,/Gaspanel/Shared/Final01,,,wOpen,rIsOpen,"
Dump01 Alias "Dump01,/Gaspanel/Shared/Dump01,,,wOpen,rIsOpen,"
N2Vent01 Alias "N2Vent01,/Gaspanel/Shared/N2Vent01,,,wOpen,rIsOpen,"
N2Vent201 Alias "N2Vent201,/Gaspanel/Shared/N2Vent201,,,wOpen,rIsOpen,"
PurgeValve Alias "PurgeValve,/Gaspanel/Shared/Purge01,,,wOpen,rIsOpen,"
}
func MapTagedAliasToChamber(chamber string, struc interface{}) []string {
attributeStruct := reflect.ValueOf(struc).Elem()
typeAttributeStruct := attributeStruct.Type()
attributes := make([]string, attributeStruct.NumField(), attributeStruct.NumField())
for i := 0; i < attributeStruct.NumField(); i++ {
alias := attributeStruct.Field(i)
tag := string(typeAttributeStruct.Field(i).Tag)
name := typeAttributeStruct.Field(i).Name
params := strings.Split(tag, ",")
alias = reflect.New(reflect.TypeOf(Alias{})).Elem()
for i := 0; i < alias.NumField(); i++ {
alias.Field(i).SetString(params[i])
}
attributeStruct.Field(i).Set(alias)
fmt.Printf("%d: %s %s = %v\n", i, name, alias.Type(), alias.Interface())
}
return attributes
}
func main() {
Attr := Manifold{}
MapTagedAliasToChamber("A", &Attr)
fmt.Println("Final01 = ", Attr.Final01.Command)
}
问题是你原来的计划,在那里你创建了一个新的名为reflect.Value
代表alias
类型*Alias
的值的38行,然后用您的信息填写,但从来没有写过它放回你的Manifold
结构。
此外,我建议你坚持标准的结构标签格式,可以通过(reflect.StructTag).Get(key string)
解析和使用更容易。并且不要在不需要它们的地方使用字符串,例如rIsOpen
听起来像一个布尔值给我。
我不知道'Tag.Get',所以一定会实现。所有别名字段都用于创建字符串,如“AT/CHA/PurgeValve/Gaspanel/Purge01.rIsOpen”,并且所有转换为布尔值等操作都在后面完成。很好的回答谢谢。 – gigatropolis 2014-11-21 15:16:49
为什么在设置之前将别名重新分配给新值? – LinearZoetrope 2014-11-21 06:50:58