我试图探索go
的类型系统,在编写一个小的副项目时很开心,但我最终遇到了一个奇怪的情况。
当一个interface
可以接受一个类型,在其中将其用于一个函数时,一个struct
实现了包含在interface
的Map中的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
转换任何内容
1条答案
按热度按时间mwg9r5ms1#
好吧,在四处挖掘之后,你可以感谢ChatGPT与Bing。
当执行“工作让我回来!!!!”