Skip to content

Bad code generated for shadowed struct fields #149

@nwidger

Description

@nwidger

If I create a package foo with the following contents:

package foo

type omit *struct{}

type Foo struct {
    NotHidden string `json:"not_hidden"`
    Hidden    string `json:"hidden"`
}

type ShortFoo struct {
    *Foo
    Hidden omit `json:"hidden,omitempty"`
}

and use it in the following main package:

package main

import (
    "encoding/json"
    "log"
)
import "github.com/nwidger/foo"

func main() {
    f := &foo.Foo{}
    sf := &foo.ShortFoo{Foo: f}
    buf, err := json.Marshal(sf)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(string(buf))
}

I get the following output:

2015/09/02 15:51:52 {"not_hidden":""}

If I then run ffjson foo.go and rerun my main package I get the following build errors:

# github.com/nwidger/foo
../foo/foo_ffjson.go:289: cannot convert mj.Hidden (type omit) to type string
../foo/foo_ffjson.go:302: ffj_t_ShortFoo_Hidden redeclared in this block
    previous declaration at ../foo/foo_ffjson.go:298
../foo/foo_ffjson.go:309: ffj_key_ShortFoo_Hidden redeclared in this block
    previous declaration at ../foo/foo_ffjson.go:305
../foo/foo_ffjson.go:529: cannot use string(string(outBuf)) (type string) as type omit in assignment

Is behavior expected? I would assume since it works with the stdlib JSON encoder it should work with ffjson. I learned about the encapsulation/shadowing/omit trick from this blog post and often use it to restrict which fields are returned by my web app.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions