结构体转换
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}
写入自己的博客中才能记得长久