convert reference type to value type in golang

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

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类型的参数,并且在这个目标函数内部我必须创建切片。

playground

英文:

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

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:

确定