Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom (Un-)Marshaller on Generic Types ignored #1021

Open
loeffert opened this issue Feb 22, 2024 · 0 comments
Open

Custom (Un-)Marshaller on Generic Types ignored #1021

loeffert opened this issue Feb 22, 2024 · 0 comments

Comments

@loeffert
Copy link

It looks like go-yaml doesn't support generics very well. Custom (Un-)Marshaller on a struct like MyType isn't called. The only way to get the Data Attribute exported is to make it public.

This is fully ignored:

type MyType[T any] struct {
	data T
}

This is exported, but the implemented MarshalYAML and UnmarshalYAML functions are never called:

https://go.dev/play/p/Fb7yQ-gAQJn

package main

import (
	"fmt"

	"gopkg.in/yaml.v3"
)

type Example struct {
	F int `yaml:"a,omitempty"`
	B int
}

type AnotherExample struct {
	B int
	C MyType[Example]
}

type MyType[T any] struct {
	Data T `yaml:"data"`
}

func (j MyType[T]) MarshalYAML() ([]byte, error) {
	fmt.Println("marshal yaml")
	return yaml.Marshal(j.Data)
}

func (j *MyType[T]) UnmarshalYAML(b []byte) error {
	fmt.Println("unmarshal yaml")
	return yaml.Unmarshal(b, &j.Data)
}

func NewMyType[T any](data T) MyType[T] {
	return MyType[T]{
		Data: data,
	}
}

func main() {
	e := Example{
		F: 1,
		B: 2,
	}
	dataE, err := yaml.Marshal(e)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(dataE))

	ae := AnotherExample{
		B: 3,
		C: NewMyType(e),
	}
	dataAE, err := yaml.Marshal(ae)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(dataAE))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant