在golang中将引用类型转换为值类型

问题描述:

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

[]Person{} is slice of Person, however, you want to have slice of pointer to Person. It should be defined as people := []*Person{personRef}.