我正在尝试探索
go
的类型系统,在编写一个小型副项目时很有趣,但最终遇到了一个奇怪的情况。
当一个
interface
可以采用一种类型,其中将其用于函数时,一个实现该 struct
的 interface
包含在 interface
的映射中,当检索时我无法投射它回到实施。为什么?如何?怎么了?
package main
import (
"context"
"fmt"
)
type State struct {
Data string
}
type InterfaceFuncs[T any] interface {
Init(ctx context.Context,
stateGetter func() T,
stateMutator func(mutateFunc func(T) T)) error
}
type ConfigWrap[T any] struct {
InterFuncs InterfaceFuncs[T]
}
type Controller[T any] struct {
mapinterfaces map[string]ConfigWrap[T]
}
func New[T any](initialState T) *Controller[T] {
return &Controller[T]{
mapinterfaces: make(map[string]ConfigWrap[T]),
}
}
func (c *Controller[T]) RegisterFuncs(pid string, config ConfigWrap[T]) error {
c.mapinterfaces[pid] = config
return nil
}
func (c *Controller[T]) InterFuncs(pid string) (*InterfaceFuncs[T], error) {
var pp ConfigWrap[T]
var exists bool
if pp, exists = c.mapinterfaces[pid]; exists {
return &pp.InterFuncs, nil
}
return nil, fmt.Errorf("InterFuncs not found")
}
func main() {
ctrl := New[State](State{})
ctrl.RegisterFuncs("something", ConfigWrap[State]{
InterFuncs: &ImpltProcFuncs{
Data: "get me back!!!!",
},
})
// why can't we cast it back to ImpltProcFuncs
getback, _ := ctrl.InterFuncs("something")
// I tried to put it as interface but doesn't works either
//// doesn't work
switch value := any(getback).(type) {
case ImpltProcFuncs:
fmt.Println("working", value)
default:
fmt.Println("nothing")
}
//// doesn't work
// tryme := any(getback).(ImpltProcFuncs) // panic: interface conversion: interface {} is *main.InterfaceFuncs[main.State], not main.ImpltProcFuncs
// fmt.Println("please", tryme.Data)
//// doesn't work
// tryme := getback.(ImpltProcFuncs)
//// doesn't work
// switch value := getback.(type) {
// case ImpltProcFuncs:
// fmt.Println("working", value)
// }
}
type ImpltProcFuncs struct {
Data string
}
func (p *ImpltProcFuncs) Init(
ctx context.Context,
stateGetter func() State,
stateMutator func(mutateFunc func(State) State)) error {
return nil
}
如何将我的
ImpltProcFuncs
作为变量返回以获得 Data
?
有什么想法吗?我错过了什么?
我以为
go
能够从interface
投射任何东西
好吧,在深入研究之后,您可以通过 Bing 感谢 ChatGPT....
if impl, ok := (*getback).(*ImpltProcFuncs); ok {
fmt.Println("working", impl.Data)
} else {
fmt.Println("not working")
}
执行“工作让我回来!!!”时