类型断言

 区分 反射

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 外的任何逻辑里面使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值