[英]Convert Composed Type in Golang
我一直在阅读Golang 中的类型别名和组合结构。 我希望能够拥有两个结构相同但可以轻松相互转换的结构。
我有一个父结构定义为:
type User struct {
Email string `json:"email"`
Password string `json:"password"`
}
一个组合结构定义为:
type PublicUser struct {
*User
}
我希望如果我定义一个User
:
a := User{
Email: "admin@example.net",
Password: "1234",
}
然后我可以执行以下类型转换:
b := (a).(PublicUser)
但它因无效的类型断言而失败:
invalid type assertion: a.(PublicUser) (non-interface type User on left)
如何在 Go 中结构相似的类型之间进行转换?
Go 中的类型断言让你可以使用接口的具体类型,而不是结构:
类型断言提供对接口值的底层具体值的访问。
https://tour.golang.org/methods/15
但是,稍加修改,此代码就可以正常工作,并且可能会按照您的预期运行:
package main
import (
"fmt"
)
type User struct {
Email string `json:"email"`
Password string `json:"password"`
}
type PublicUser User
func main() {
a := User{
Email: "admin@example.net",
Password: "1234",
}
fmt.Printf("%#v\n", a)
// out: User{Email:"admin@example.net", Password:"1234"}
b := PublicUser(a)
fmt.Printf("%#v", b)
// out PublicUser{Email:"admin@example.net", Password:"1234"}
}
这里, PublicUser
是对User
类型的重新定义; 最重要的是,它是一个独立的类型,共享字段,但不共享 User 的方法集( https://golang.org/ref/spec#Type_definitions )。
然后,您可以简单地使用 PublicUser 类型构造函数,因为您可能已经对string
/ []byte
转换做了类似的[]byte
: foo := []byte("foobar")
。
另一方面,如果您要使用实际的类型别名( type PublicUser = User
),您的输出将列出User
作为两个实例的类型:PublicUser 只是旧事物的新名称,而不是新类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.