convert reference type to value type in golang

huangapple go评论106阅读模式
英文:

convert reference type to value type in golang

问题

我想创建一个类型为*Person的元素切片。

  1. package main
  2. type Person struct {
  3. Name string
  4. }
  5. func convertRefTypeToType(refPerson *Person) Person {
  6. // 是否可以将*Person转换为Person
  7. return Person{}
  8. }
  9. func main() {
  10. personRef := &Person{Name: "Nick"}
  11. person := convertRefTypeToType(personRef)
  12. people := []Person{personRef} // person
  13. }

但是出现了错误:

  1. ./refConvert.go:16: cannot use personRef (type *Person) as type Person in array element

是否可以将类型为*Person的元素转换为类型为Person的元素?这个需求可能看起来很奇怪,但我的目标函数接受*Person类型的参数,并且在这个目标函数内部我必须创建切片。

playground

英文:

I want to create slice of elements of type *Person.

  1. package main
  2. type Person struct {
  3. Name string
  4. }
  5. func convertRefTypeToType(refPerson *Person) Person {
  6. // is it possible to convert *Person to Person
  7. return Person{}
  8. }
  9. func main() {
  10. personRef := &Person{Name: "Nick"}
  11. person := convertRefTypeToType(personRef)
  12. people := []Person{personRef} // person
  13. }

But have error:

  1. ./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}.

huangapple
  • 本文由 发表于 2014年12月27日 10:55:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/27663973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定