Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

Golang: response struct having multiple possible types for field

Writer Mia Lopez

I want to send a response from my api with a unified structure for all responses

type formattedResponse struct { Status string Data []dataStruct
}
type dataStruct struct { Name string Phone string
}

I want to have Data be able to be different structs and not just the single dataStruct. I can tell that i'm not using this pattern correctly. What is the correct way to accomplish this sort of thing? Is there a way to have a struct field be able to be any type with the same key?

3

2 Answers

I guess this is what you need - you would like to use the same "base" struct with different field types:

package main
type formattedResponse struct { Status string Data interface{}
}
type dataStruct1 struct { Name string Phone string
}
type dataStruct2 struct { Office string Location string
}
func main() { // using formattedResponse with dataStruct1 fr1 := formattedResponse{ Status: "ok", } if fr1.Data == nil { fr1.Data = make([]dataStruct1, 0) } fr1.Data = append(fr1.Data.([]dataStruct1), dataStruct1{Name: "n1", Phone: "12345"}) // using formattedResponse with dataStruct2 fr2 := formattedResponse{ Status: "ok", } if fr2.Data == nil { fr2.Data = make([]dataStruct2, 0) } fr2.Data = append(fr2.Data.([]dataStruct2), dataStruct2{Office: "o2", Location: "Paris"})
}

@archaeopteryx what you could do is define the returned Data property as an Interface. See my example below,

type Data interface { LogData() string
}
type formattedResponse struct { Status string Data []Data
}
type userData struct { Name string Phone string
}
func (u userData) LogData() string { fmt.Sprintln("This is some shared function")
}

You'd ideally come up with a function more useful than LogData that can be shared by all returned types but hopefully you get the idea. As long as another struct has the same function(s) within the interface it will implement it, and so satisfy as being part of the returned slice

I hope that makes sense!

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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