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

相关推荐
Justin3go1 天前
HUNT0 上线了——尽早发布,尽早发现
前端·后端·程序员
Tony Bai1 天前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
wjs20241 天前
Swift 类型转换
开发语言
一线大码1 天前
SpringBoot 3 和 4 的版本新特性和升级要点
java·spring boot·后端
秃了也弱了。1 天前
python实现定时任务:schedule库、APScheduler库
开发语言·python
weixin_440730501 天前
java数组整理笔记
java·开发语言·笔记
weixin_425023001 天前
Spring Boot 配置文件优先级详解
spring boot·后端·python
weixin_425023001 天前
Spring Boot 实用核心技巧汇总:日期格式化、线程管控、MCP服务、AOP进阶等
java·spring boot·后端
一线大码1 天前
Java 8-25 各个版本新特性总结
java·后端
Thera7771 天前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++