goccy / go-yaml

YAML support for the Go language
MIT License
1.12k stars 129 forks source link

Support generic map slice #422

Open renom opened 7 months ago

renom commented 7 months ago

Example:

package main

import "fmt"

type MapItem[K, V any] struct {
    Key   K
    Value V
}

type SpecificMapValue struct {
    Field1 string
    Field2 int
    Field3 bool
}

func main() {
    var mapSlice []MapItem[string, SpecificMapValue]
    // next we should do unmarshalling:
    // yaml.Unmarshal([]byte("some yaml here"), &mapSlice)
    // but generic map slices aren't supported yet
    fmt.Println(mapSlice)
}
renom commented 7 months ago

Would it be enough to make MapItem an interface here? Something like that:

type MapItem interface {
    KeyToAny() interface{}
    ValueToAny() interface{}
}

Then the generic MapSlice implementation would be out of go-yaml's scope. E.g. the following code could be used in the app:

type MapSlice[K, V any] []MapItem[K, V]

type MapItem[K, V any] struct {
    Key   K
    Value V
}

func (m MapItem[K, V]) KeyToAny() interface{} {
    return m.Key
}

func (m MapItem[K, V]) ValueToAny() interface{} {
    return m.Value
}

Or the latter code could be on the go-yaml's side too.