duandu5846 2013-08-27 17:35
浏览 64
已采纳

Golang:获取具有字段名称作为字符串的基础结构

How can I get the underlying value of a field having the fields name as a string?

I understand I need to use reflection but if I do will I have to continue using it throughout my code? Is there any way to assert?

I would just like to get the value of the field, the underlying struct, in this case a []Dice.

http://play.golang.org/p/KYOH8C7TAl

type Dice struct {
    In int
}

type SliceNDice struct {
    Unknown []Dice
}

func main() {
    structure := SliceNDice{make([]Dice, 10)}

    refValue := reflect.ValueOf(&structure).Elem().FieldByName(string("Unknown"))
    slice := refValue.Slice(0, refValue.Len())

    // cannot range over slice (type reflect.Value)
    //for i,v := range slice {
    //    fmt.Printf("%v %v
", i, v.In)
    //}

    for i := 0; i < slice.Len(); i++ {
        v := slice.Index(i)
        // v.In undefined (type reflect.Value has no field or method In)
        fmt.Printf("%v %v
", i, v.In)
    }

}
  • 写回答

1条回答 默认 最新

  • doufuxing8562 2013-08-27 19:35
    关注

    If you know that the "Unknown" field is of type []Dice, you can use Value.Interface to get the underlying value and convert it with a type assertion:

    slice := refValue.Interface().([]Dice)
    
    for i,v := range slice {
         fmt.Printf("%v %v
    ", i, v.In)
    }
    

    http://play.golang.org/p/2lV106b6dH

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。
  • ¥15 已知隐函数其中一个变量τ的具体值,求另一个变量