如何从 `func() *int` 转换为 `func() interface{}`?
How to convert from `func() *int` to `func() interface{}`?
我想要类似以下功能的东西:
func decorateFn(fn func() interface{}) interface{} {
decorate()
return fn()
}
func decorateFnInt(fn func() *int) *int {
return decorateFn(fn).(*int)
}
使用decorateFn((func() interface{})(fn)).(*int)
无效。是否可以将 func() *int
转换为 func() interface{}
?如果可以,怎么做?
使用 go 1.18
您可以使用泛型来实现这一点 - 确保 compile-time 类型安全并且没有运行时类型断言:
func decorateFn[T any](fn func() T) T {
decorate()
return fn()
}
func decorateFnInt(fn func() *int) *int {
return decorateFn(fn)
}
可以通过检查 fn
的类型在 compile-time 推断出函数 decorateFn
的类型约束。
https://go.dev/play/p/AAByiBFRQch
编辑:如果你被困在go 1.17
上并且不能使用泛型,你可以使用interface{}
对于函数参数,但任何类型决定都必须在运行时执行。你可以试试 type switch:
func decorateFn(v interface{}) interface{} {
decorate()
switch t := v.(type) {
case func() *int:
return t()
case func() *string:
return t()
default:
panic(fmt.Sprintf("unsupported type: %T", v))
}
}
我想要类似以下功能的东西:
func decorateFn(fn func() interface{}) interface{} {
decorate()
return fn()
}
func decorateFnInt(fn func() *int) *int {
return decorateFn(fn).(*int)
}
使用decorateFn((func() interface{})(fn)).(*int)
无效。是否可以将 func() *int
转换为 func() interface{}
?如果可以,怎么做?
使用 go 1.18
您可以使用泛型来实现这一点 - 确保 compile-time 类型安全并且没有运行时类型断言:
func decorateFn[T any](fn func() T) T {
decorate()
return fn()
}
func decorateFnInt(fn func() *int) *int {
return decorateFn(fn)
}
可以通过检查 fn
的类型在 compile-time 推断出函数 decorateFn
的类型约束。
https://go.dev/play/p/AAByiBFRQch
编辑:如果你被困在go 1.17
上并且不能使用泛型,你可以使用interface{}
对于函数参数,但任何类型决定都必须在运行时执行。你可以试试 type switch:
func decorateFn(v interface{}) interface{} {
decorate()
switch t := v.(type) {
case func() *int:
return t()
case func() *string:
return t()
default:
panic(fmt.Sprintf("unsupported type: %T", v))
}
}