如何在Go中创建自定义类型元素的自定义类型数组?

时间:2014-02-15 23:10:01

标签: arrays go

我正在尝试创建一个名字和薪水的人,然后是一群人。我在“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)
}

1 个答案:

答案 0 :(得分:3)

您将指针的切片构造为person。这就是为什么你应该指出你ab

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)
}

替代方法是将ab定义为结构的指针。

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)
}