首頁  >  文章  >  後端開發  >  為什麼 Go 不能強制轉換實作泛型的介面?

為什麼 Go 不能強制轉換實作泛型的介面?

WBOY
WBOY轉載
2024-02-05 21:27:03546瀏覽

为什么 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!!!!」

以上是為什麼 Go 不能強制轉換實作泛型的介面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除