英文:
How do I make a customized type array of customized type elements in Go?
问题
我正在尝试创建一个具有姓名和薪水的人,然后创建一个人的数组。在"data[0] = a"处出现的错误是:"无法将a(person类型)用作*person类型的赋值。"我是否需要进行某种类型转换,就像在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)
}
注意:我已经将代码中的注释翻译成了中文。
英文:
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)
}
答案1
得分: 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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论