我正在尝试创建一个名字和薪水的人,然后是一群人。我在“data [0] = a”处得到的错误表明:“不能使用(类型人)作为类型*人员。”我需要做某种类型的转换,就像在Java中一样吗?
package main
import "fmt"
type person struct {
name string
salary float64
}
type people []*person
func main() {
var data = make(people, 10)
var a person
var b person
a.name = "John Smith"
a.salary = 74000
b.name = "Jane Smith"
b.salary = 82000
data[0] = a
data[1] = b
fmt.Print(data)
}
答案 0 :(得分:3)
您将指针的切片构造为person
。这就是为什么你应该指出你a
和b
。
package main
import "fmt"
type person struct {
name string
salary float64
}
type people []*person
func main() {
var data = make(people, 10)
var a person
var b person
a.name = "John Smith"
a.salary = 74000
b.name = "Jane Smith"
b.salary = 82000
data[0] = &a
data[1] = &b
fmt.Print(data)
}
替代方法是将a
和b
定义为结构的指针。
package main
import "fmt"
type person struct {
name string
salary float64
}
type people []*person
func main() {
var data = make(people, 10)
a := &person{}
b := &person{}
a.name = "John Smith"
a.salary = 74000
b.name = "Jane Smith"
b.salary = 82000
data[0] = a
data[1] = b
fmt.Print(data)
}