I'm attempting to create a person with a name and salary, then an array of persons. The error I get at "data[0] = a" states: "cannot use a (type person) as type *person in assignment." Is there some sort of casting I need to do, as in 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)
}
You construct slice of pointers to person
. That's why you should take pointer of you a
and 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)
}
Alternative approach is to define a
and b
as pointers to structs.
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.