2014-02-15 85 views
1

我正在嘗試創建一個名字和薪水的人,然後是一羣人。我在「data [0] = a」指出:「的錯誤不能在作業中使用(類型人員)作爲類型*人員。」是否有某種類型的演員需要我去做,如在Java中?如何在Go中創建自定義類型元素的自定義類型數組?

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

回答

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

或者只是'數據[0] =人{ 「約翰·史密斯」,74000}' – Dustin

+0

'數據:=人{{ 「約翰·史密斯」,74000},{ 「簡·史密斯」,82000}}' –

相關問題