I am trying to write a function which can be used by different structs. The return of the function has to be a slice of the corresponding struct. Thus I need a function which accept a struct as a parameter and return a slice. My code somehow looks like this but I have no idea how can I wrap it as a function?
type name struct{
FirstName string `xml:"firstName"`
LastName string `xml:"lastName"`
}
fileList := TreeTraversal(".")
var a name
var b []name
for i := 0; i < len(fileList); i++{
fileByte, _ := ioutil.ReadFile(fileList[i])
xml.Unmarshal(fileByte, &a)
b = append(b, a)
}
As far as I know I can pass a struct to a function as an interface, but I have no idea about the return type?
If you want a function that takes any struct type and returns a slice of it, like:
func MakeSlice(s ANY_STRUCT_TYPE) []ANY_STRUCT_TYPE
You're looking for generics, which Go doesn't currently support. See this FAQ entry.
The Go team is working to add generics to the language - it's a work in progress, and everyone is free to participate in the discussion. Once generics exist, they will provide the solution you seek here.
In the meantime, you could use code generation or think of a slightly different design for your problem. Some code duplication is OK too, Go doesn't frown upon it as badly as some other languages.