区分 反射
kit:
commonResponse.Err(commonErrors.ErrUserIDNotFound())
common:
// 无法获取请求中的用户 ID
func ErrUserIDNotFound() Error {
return Error{
Code: UserIDNotFound,
Msg: "无效的用户",
}
}
type Error struct {
Code model.ErrorType `json:"code"`
Msg string `json:"msg"`
}
func Err(err error) Response {
if eErr, ok := err.(errors.Error); ok {
return Response{
Code: eErr.Code,
Msg: eErr.Msg,
}
}
logrus.Error(err)
return Response{
Code: errors.Unknown,
Msg: "未知错误",
}
}
value,ok := x.(T)
x表示一个接口的类型,T表示一个类型(也可为接口类型 见:
https://blog.csdn.net/chushoufengli/article/details/104793425)
该断言表达式会返回x的值和一个布尔值 可根据该布尔值判断x是否为T类型
-- 注意 1:
func HandleAuctionInfoReq(conn nw.Conn, p interface{}) (nw.ProtoMessage, error) {
req := p.(*pb.AuctionInfoReq) //(断言失败的话,返回panic)
//req, _ := p.(*pb.AuctionInfoReq) 可以接收两个或一个参数 (断言失败的话,不返回panic,req的值会是nil)
}
-- 注意 2:
可以类型重用
if w, ok := w.(*os.File); ok {
// ...use w...
}
配合switch使用
func main() {
var a int
a = 10
judgeType(a)
}
func judgeType(a interface{}) {
switch a.(type) {
case int:
fmt.Println("the type of a is int")
case string:
fmt.Println("the type of a is string")
case float64:
fmt.Println("the type of a is float")
default:
fmt.Println("unknown type")
}
}
注意:在switch结构中使用了 switch a.(type),该element.(type)语法不能在 switch 外的任何逻辑里面使用