doulin6761
2014-12-27 02:55
浏览 137
已采纳

在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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzouche9108 2014-12-27 03:11
    已采纳

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题