初始化结构体从字符串列表中

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

Initialize structs from list of strings

问题

我正在尝试从字符串列表初始化结构体,但编译器报错如下。我还在学习这门语言,所以请原谅我的无知,这个问题可以通过使用类型断言来解决吗?

错误:v.UberX 未定义(类型 string 没有 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
    }
}
英文:

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

得分: 2

你的Galaxy结构体甚至没有存储名称,在你的尝试中,名称和结构体值之间没有任何连接。将名称添加到结构体中:

type Galaxy struct {
    Name  string
    UberX int64
    UberY int64
}

接下来,在你的第一个循环中,你创建了一个*Galaxy值,但你只将它存储在一个局部变量v中,这个变量遮蔽了循环变量v

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

你需要一个Galaxy切片或*Galaxy切片来填充:

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

然后,只需要一个循环来遍历星系名称并填充gs切片:

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

验证结果:

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

输出结果(在Go Playground上尝试):

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

建议先学习Golang Tour来了解基础知识。

英文:

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\n", 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.

huangapple
  • 本文由 发表于 2016年11月15日 18:45:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/40607811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定