结构体转换

package main
import "fmt"
type Student struct{
	Age int
}

type Person struct {
	Age int
}

type Stu Student
func main(){
	//【1】结构体是用户单独定义的类型,和其它类型进行转换时需要有完全相同的字段(名字、个数和类型)
	var s Student = Student {10}
	fmt.Println(s)
	var p Person = Person{12}
	//s = p // 不能这样直接赋值, a4.go:16:4: cannot use p (type Person) as type Student in assignment
	s = Student(p)  // 只能通过结构体强转
	fmt.Println(s)
	fmt.Println(p)


	//【2】结构体进行type重新定义(相当于取别名),Golang认为是新的数据类型,但是相互间可以强转
	var s1 Student = Student{19}
	fmt.Println(s1)
	var s2 Stu = Stu{20}
	s1 =Student(s2)
	fmt.Println(s1)
	fmt.Println(s2)
}

输出

{10}
{12}
{12}
{19}
{20}
{20}
posted @   ty1539  阅读(94)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示