为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕沐林林 2021-09-10 15:30:05
我想创建类型的元素切片*Person。package maintype 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是否可以将 type*Person元素转换为 type元素Person?这种愿望可能看起来很奇怪,但我的目标函数接受类型参数,*Person并且在此目标函数中我必须创建切片。

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

[]Person{}是 的切片Person,但是,您希望拥有指向Person. 它应该被定义为people := []*Person{personRef}


查看完整回答
反对 回复 2021-09-10

没有找到匹配的内容?试试慕课网站内搜索吧

添加回答

代码语言

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号