douxie1692 2016-11-15 10:45
浏览 18
已采纳

从字符串列表初始化结构

I'm trying to initialize structs from a list of strings, but the compiler is throwing the following error. I'm still learning the language so excuse my ignorance, but is this solved by utilizing type assertion?

ERROR: v.UberX undefined (type string has no field method UberX)

type Galaxy struct {
    UberX     int64
    UberY     int64
}

func main() {
    galaxies := []string{"andromeda", "milkyway", "maffei"}
    for _, v := range galaxies {
        v := &Galaxy{}
    }
    for _, v := range galaxies {
        v.UberX += 1000
        v.UberY += 750
    }
}
  • 写回答

1条回答 默认 最新

  • duanmei1922 2016-11-15 10:58
    关注

    Your Galaxy struct doesn't even store the name, in your attempt there isn't any connection between the names and the struct values. Add the name to the struct:

    type Galaxy struct {
        Name  string
        UberX int64
        UberY int64
    }
    

    Next, in your first loop you create a *Galaxy value, but you only store it in a local variable v which by the way shadows the loop variable v:

    for _, v := range galaxies {
        v := &Galaxy{}
    }
    

    You need a slice of Galaxy or a slice of *Galaxy which you can populate:

    gs := make([]*Galaxy, len(galaxies))
    

    Then 1 loop is enough to loop over the galaxy names and populate the gs slice:

    for i, v := range galaxies {
        gs[i] = &Galaxy{
            Name:  v,
            UberX: 1000,
            UberY: 750,
        }
    }
    

    Verifying the result:

    for _, v := range gs {
        fmt.Printf("%+v
    ", v)
    }
    

    Output (try it on the Go Playground):

    &{Name:andromeda UberX:1000 UberY:750}
    &{Name:milkyway UberX:1000 UberY:750}
    &{Name:maffei UberX:1000 UberY:750}
    

    Recommended to go through the Golang Tour first to learn the basics.

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

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏