卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章33935本站已运行390

为什么 Go 不能强制转换实现泛型的接口?

为什么 go 不能强制转换实现泛型的接口?

问题内容

我正在尝试探索 Go 的类型系统,并在编写一个小型副项目时获得乐趣,但最终遇到了一个奇怪的情况。

当一个 interface 可以采用一个类型(其中将其用于函数)时,一个 struct 实现该 interface ,该 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")
    }

执行时,它输出“working get me back!!!!”

卓越飞翔博客
上一篇: 如何在构建 ARM64 二进制文件时忽略gotvm
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏