Maison  >  Article  >  développement back-end  >  Pourquoi Go ne peut-il pas diffuser des interfaces qui implémentent des génériques ?

Pourquoi Go ne peut-il pas diffuser des interfaces qui implémentent des génériques ?

WBOY
WBOYavant
2024-02-05 21:27:03546parcourir

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

Contenu de la question

J'essayais d'explorer le système de types de Go et de m'amuser à écrire un petit projet parallèle, mais j'ai fini par me retrouver dans une situation étrange.

Lorsqu'un interface 可以采用一个类型(其中将其用于函数)时,一个 struct 实现该 interface ,该 interface 包含在 interface est sur la carte, je ne peux pas le reconvertir en implémentation lors de sa récupération. Pourquoi? comment ? Qu'est-ce qui ne va pas?

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
}

Comment utiliser ImpltProcFuncs 作为变量返回以获取 Data ?

Qu'est-ce que j'ai raté ?

Je pense que Go est capable de retourner n'importe quoi depuis interface.


Bonne réponse


Eh bien, après avoir creusé plus profondément, vous pouvez utiliser Bing grâce à ChatGPT...

if impl, ok := (*getback).(*ImpltProcFuncs); ok {
        fmt.Println("working", impl.Data)
    } else {
        fmt.Println("not working")
    }

Une fois exécuté, il affiche "Je travaille, récupérez-moi !!!!"

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer