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 底层实现。。

相关推荐
华仔啊16 小时前
千万别给数据库字段加默认值 null!真的会出问题
java·数据库·后端
IT_陈寒18 小时前
别再死记硬背Python语法了!这5个思维模式让你代码量减半
前端·人工智能·后端
xyy12319 小时前
C# 读取 appsettings.json 配置指南
后端
code_YuJun20 小时前
Spring ioc 完全注解
后端
kevinzeng20 小时前
反射的初步理解
后端·面试
下次一定x20 小时前
深度解析 Kratos 客户端服务发现与负载均衡:从 Dial 入口到 gRPC 全链路落地(上篇)
后端·go
kevinzeng20 小时前
Spring 核心知识点:EnvironmentAware 接口详解
后端
xyy12320 小时前
C# / ASP.NET Core 依赖注入 (DI) 核心知识点
后端
yuhaiqiang1 天前
为什么我建议你不要只问一个AI?🤫偷偷学会“群发”,答案准到离谱!
人工智能·后端·ai编程
双向331 天前
AR 眼镜拯救社恐:我用 Kotlin 写了个拜年提词器
后端