go switch 与 interface

go switch 与 interface

前言

github.com/google/cel-go/common/types/ref

go 复制代码
type Val interface {
	// ConvertToNative converts the Value to a native Go struct according to the
	// reflected type description, or error if the conversion is not feasible.
	ConvertToNative(typeDesc reflect.Type) (interface{}, error)

	// ConvertToType supports type conversions between value types supported by
	// the expression language.
	ConvertToType(typeValue Type) Val

	// Equal returns true if the `other` value has the same type and content as
	// the implementing struct.
	Equal(other Val) Val

	// Type returns the TypeValue of the value.
	Type() Type

	// Value returns the raw value of the instance which may not be directly
	// compatible with the expression language types.
	Value() interface{}
}

当我们实现了一个interface时,使用swtich case去判断,会命中哪条结果?

go 复制代码
switch i := v.(type) {
	case ref.Val:
		return resolveType(i.Value())
	case *CustomType:
		return resolveType(i.Value())
	default:
		
	}

经过测试发现,谁的case靠前,会命中谁,哪怕CustomType有一些私有方法

后面空了看看switch 底层实现。。

相关推荐
程序员爱钓鱼33 分钟前
Go语言实战案例-简易计算器(加减乘除)
后端
学不会就看37 分钟前
Django--01基本请求与响应流程
后端·python·django
AI+程序员在路上41 分钟前
Qt6中模态与非模态对话框区别
开发语言·c++·qt
nbsaas-boot6 小时前
Java 正则表达式白皮书:语法详解、工程实践与常用表达式库
开发语言·python·mysql
chao_7896 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
Nejosi_念旧6 小时前
解读 Go 中的 constraints包
后端·golang·go
风无雨6 小时前
GO 启动 简单服务
开发语言·后端·golang
小明的小名叫小明6 小时前
Go从入门到精通(19)-协程(goroutine)与通道(channel)
后端·golang
光影少年6 小时前
从前端转go开发的学习路线
前端·学习·golang
斯普信专业组6 小时前
Go语言包管理完全指南:从基础到最佳实践
开发语言·后端·golang