0

Say I have a struct that I bind json param data to like

type User struct {
  FirstName string `json:"firstName"`
}

The attribute FirstName has to be capitalized so that the json values can be binded to the struct.

But I also want to create an interface to accept any struct that has a FirstName like attribute. Since FirstName is already capitalized and taken, I have to name the method something else.

type NameInterface interface {
    FirstName() string // nope
    FirstNameValue() string // maybe?
}

But it seems really weird to have to add a helper function for each attribute on all my json structs just so they can work with an interface. Is there something I'm misunderstanding or a programming pattern I'm missing? What is the best way to get a json struct to work with interfaces in go?

More (what I am trying to do):

I want to parse json params that are coming from my controllers into structs. And then pass that struct data into filters which then run sql commands to filter data based on the params data. I wanted to use interfaces so I can pass in structs created from different sources into my filters.

1
  • Your "More" info sounds like your filters should work on interfaces while the JSON decoding happens completely on material structs which sounds reasonable and you do not need to JSON decode into interfaces. Maybe you should show real code as I cannot see any difficulty here: What is wrong implementing the methods your structs need to have to conform to an interface? Commented Feb 21, 2016 at 9:39

1 Answer 1

2

Interfaces in Go specify behaviour, but you're trying to use them to describe data. This is why you're finding your approach to be difficult - and it's also why it's probably the wrong approach.

It's difficult to give a more specific answer without knowing what you're really trying to achieve, but if you, for example, want to be able to have functions that can read specific named fields from different struct types, you'll probably want to define one struct to describe this data and then embed that struct into other struct types.

Something like this might fit your needs:

type Person struct {
    FirstName string `json:"firstName"`
}

type User struct {
    Person
    // other User-specific fields
}

type Admin struct {
    Person
    // other Admin-specific fields
}

func Harass(p Person) { }

func main() {
    user := User{Person{"Frank"}}
    Harass(user.Person)
    admin := Admin{Person{"Angelina"}}
    Harass(admin.Person)
}
Sign up to request clarification or add additional context in comments.

1 Comment

added more info to my question. Really appreciate your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.