go icon indicating copy to clipboard operation
go copied to clipboard

Marshaling niladic methods on struct to their values

Open gwennlbh opened this issue 3 years ago • 0 comments

Is it possible, when marshaling a struct, to add fields with keys set to the method's name and values corresponding to the result of niladic methods?

An example:

type A struct {
    Foo string
    Bar string
}

type (a A) Baz() int {
    return len(a.Foo) + len(a.Bar)
}

a := A{
    Foo: "spam",
    Bar: "eggs",
}

Marshaling a would result in the following JSON:

{
    "Foo": "spam",
    "Bar": "eggs",
    "Baz": 8
}

Is it possible to achieve this behaviour? If not, can it be implemented? I'm willing to try my hand at a PR.

gwennlbh avatar May 15 '22 06:05 gwennlbh