我想创建 *Person
类型的元素 slice 。
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
}
但有错误:
./refConvert.go:16: cannot use personRef (type *Person) as type Person in array element
是否可以将 *Person
类型的元素转换为 Person
类型的元素?
这种愿望可能看起来很奇怪,但我的目标函数接受类型为 *Person
的参数,并且在这个目标函数中我必须创建 slice 。
playground
最佳答案
[]Person{}
是 Person
的 slice ,但是,您想要指向 Person
的指针 slice 。
它应该定义为 people := []*Person{personRef}
。
关于go - 在golang中将引用类型转换为值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663973/