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

相关推荐
涡能增压发动积9 小时前
同样的代码循环 10次正常 循环 100次就抛异常?自定义 Comparator 的 bug 让我丢尽颜面
后端
Wenweno0o9 小时前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
swg3213219 小时前
Spring Boot 3.X Oauth2 认证服务与资源服务
java·spring boot·后端
tyung9 小时前
一个 main.go 搞定协作白板:你画一笔,全世界都看见
后端·go
gelald9 小时前
SpringBoot - 自动配置原理
java·spring boot·后端
chenjingming66610 小时前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
cch891810 小时前
Python主流框架全解析
开发语言·python
不爱吃炸鸡柳10 小时前
C++ STL list 超详细解析:从接口使用到模拟实现
开发语言·c++·list
十五年专注C++开发10 小时前
RTTR: 一款MIT 协议开源的 C++ 运行时反射库
开发语言·c++·反射
Momentary_SixthSense10 小时前
设计模式之工厂模式
java·开发语言·设计模式