自定义数据类型
- 在Go语言中,自定义数据类型指的是使用
type
关键字来进行定义新的类型,他可以是基本类型的别名,也可以是结构体、函数等组合而成的新类型。 - 自定义类型能够更好地抽象和封装,让代码更加的易读、易懂、易维护。
例如给前端反映一个状态码:
package main // 前端状态码:1001 1002 1003 1004 // 每个状态码都有对应的信息 // 所以我们定义一个类型 type Code int // 但现在这些都是int类型,还不够间洁 const ( SuccessCode Code = 0 //成功 NetworkErrorCode Code = 1001 //网络错误 ServiceErrorCode Code = 1002 //服务错误 ) // 未自定义类型的时候:但是问题来了,getCodeMsg()里随便输入数字都可以,这样容易有问题 // func webServer(name string) (code int, msg string) { //func webServer(name string) (code Code, msg string) { // if name == "1" { // return NetworkErrorCode, getCodeMsg(NetworkErrorCode) // } // if name == "2" { // return ServiceErrorCode, getCodeMsg(ServiceErrorCode) // } // return SuccessCode, getCodeMsg(SuccessCode) //} // 自定义了类型之后code就不是int类型了,是Code类型。 // 但这样就有了冗余代码,下面会有一个新的方法来解决。 // func getCodeMsg(code int) (msg string) { //func getCodeMsg(code Code) (msg string) { // switch code { // case SuccessCode: // return "成功" // case ServiceErrorCode: // return "服务错误" // case NetworkErrorCode: // return "网络错误" // } // return "" //} // 消除冗余之后的代码 func (c Code) getMsg() string { switch c { case SuccessCode: return "成功" case ServiceErrorCode: return "服务错误" case NetworkErrorCode: return "网络错误" } return "" } // 消除冗余代码之后,使用变得更易懂了、更好维护了 //func webServer(name string) (code Code, msg string) { // if name == "1" { // return NetworkErrorCode, NetworkErrorCode.getMsg() // } // if name == "2" { // return ServiceErrorCode, ServiceErrorCode.getMsg() // } // return SuccessCode, SuccessCode.getMsg() //} // 甚至我们可以让一个对象用两个方法来获取想要的值 // 例如我们让code自己返回自己还有它自身所携带的msg func (c Code) getCodeandMsg() (code Code, msg string) { return c, c.getMsg() } // 狠狠地优化!代码更加精简了 func webServer(name string) (code Code, msg string) { if name == "1" { return NetworkErrorCode.getCodeandMsg() } if name == "2" { return ServiceErrorCode.getCodeandMsg() } return SuccessCode.getCodeandMsg() } func main() { }
类型别名
和自定义类型很像,但是有一些地方又和自定义类型有很大的差距。例如:
- 类型别名不能绑定方法。(这个是最大区别,因为能绑方法就多了很多能做的事)
- 打印类型还是原始类型。
- 和原始类型比较的时候,类型别名不用转换。
- 从自定义类型的角度来说,自定义的类型虽然是int,但和int声明的值相互比较时,这个就和
int
与int32
之间的区别,看起来似乎一样,但实际底层又不一样,必须调用方法相互转换才能比较。 - 而类型别名就只是给了个别名,本质上还是
int
和int
。
type MyCode int //自定义类型
type MyOtherCode = int //类型别名
评论(0)