Question

A struct I'm working on called fieldDefinition holds metadata about a field used by an object in my web app. One of the fields on fieldDefinition (it does get a bit confusing) looks something like this:

type fieldDefinition struct {
    id string
    apiName string
    label string
    fieldType uint //Defined by a list of constants.
    defaultValue interface{}
}

I also have a function* on the struct to retrieve the default value (setting it requires a bit of logic) which currently literally just returns the interface{} type. Depending on the value of fieldType I would like there to be some indication that the value returned is useable as the type fieldType says it should be.

For example, if fieldType == FT_GEOLOCATION, then I want to make sure the interface value returned is of my Geolocation struct. I was looking at type assertions but I can't see any examples of it being used in a similar situation to learn from, and I don't think I'm 100% sure of how they actually work.

How could I benefit from type assertions here, and is there any better/more accepted way of doing this, or do I just have to accept that interface{} types are difficult to ensure validity with?

No correct solution

OTHER TIPS

It sounds like you want a type switch statement.

Each switch case could check that the fieldType is set correctly.

Licensed under: CC-BY-SA with attribution
scroll top