英文:
convert reference type to value type in golang
问题
我想创建一个类型为*Person的元素切片。
package main
type Person struct {
Name string
}
func convertRefTypeToType(refPerson *Person) Person {
// 是否可以将*Person转换为Person
return Person{}
}
func main() {
personRef := &Person{Name: "Nick"}
person := convertRefTypeToType(personRef)
people := []Person{personRef} // person
}
但是出现了错误:
./refConvert.go:16: cannot use personRef (type *Person) as type Person in array element
是否可以将类型为*Person的元素转换为类型为Person的元素?这个需求可能看起来很奇怪,但我的目标函数接受*Person类型的参数,并且在这个目标函数内部我必须创建切片。
英文:
I want to create slice of elements of type *Person.
package main
type Person struct {
Name string
}
func convertRefTypeToType(refPerson *Person) Person {
// is it possible to convert *Person to Person
return Person{}
}
func main() {
personRef := &Person{Name: "Nick"}
person := convertRefTypeToType(personRef)
people := []Person{personRef} // person
}
But have error:
./refConvert.go:16: cannot use personRef (type *Person) as type Person in array element
Is it possible to convert element of type *Person to element of type Person?
This desire may seem weird but my target function accepts argument of type *Person and inside this target function I have to create slice.
playground
答案1
得分: 3
[]Person{} 是 Person 的切片,然而,你想要一个指向 Person 的指针的切片。
应该这样定义:people := []*Person{personRef}。
英文:
[]Person{} is slice of Person, however, you want to have slice of pointer to Person.
It should be defined as people := []*Person{personRef}.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论