I have those 2 almost exact functions :
Number 1:
func mergeSlicesOfRequestObjects(aSliceDestination *[]RequestObject, aSliceSource []RequestObject) {
for _, oSliceSourceItem := range aSliceSource {
// Get current key
iIndexSourceItemFound := -1
for iIndexAttribute, oSliceDestinationItem := range *aSliceDestination {
if oSliceSourceItem.Key == oSliceDestinationItem.Key {
iIndexSourceItemFound = iIndexAttribute
break
}
}
// Update attribute
if iIndexSourceItemFound == -1 {
*aSliceDestination = append(*aSliceDestination, oSliceSourceItem)
}
}
}
Number 2:
func mergeSlicesOfResponseObjects(aSliceDestination *[]ResponseObject, aSliceSource []ResponseObject) {
for _, oSliceSourceItem := range aSliceSource {
// Get current key
iIndexSourceItemFound := -1
for iIndexAttribute, oSliceDestinationItem := range *aSliceDestination {
if oSliceSourceItem.Key == oSliceDestinationItem.Key {
iIndexSourceItemFound = iIndexAttribute
break
}
}
// Update attribute
if iIndexSourceItemFound == -1 {
*aSliceDestination = append(*aSliceDestination, oSliceSourceItem)
}
}
}
As you can see the only difference is the struct type of the arguments of the functions.
So here is my question : is there any way to merge those 2 functions into one ?
I've tried using interfaces but I can't figure it out...
Thanks for all the answer in advance :)
Cheers
EDIT
I've implemented thwd answer but I'm getting errors. Here's what I've done:
type Request struct {
Headers []RequestObject
}
type RequestObject {
Key string
}
type Keyer interface {
GetKey() string
}
func (oRequestObject RequestObject) GetKey() string {
return oRequestObject.Key
}
func mergeKeyers(aDst *[]Keyer, aSrc []Keyer) {
// Logic
}
func test() {
// rDst and rSrc are Request struct
mergeKeyers(&rDst.Headers, rSrc.Headers)
}
And I'm getting the following errors when executing test():
cannot use &rDst.Headers (type *[]RequestObject) as type *[]Keyer in argument to mergeKeyers
cannot use rSrc.Headers (type []RequestObject) as type []Keyer in argument to mergeKeyers
Any idea why ?