I want to be able to pass a slice of a particular type into a function that will populate it with more items of that type. Here is an example of code does not compile, but describes what I want to achieve:
package main
import (
"log"
"reflect"
"strings"
)
type Person struct {
Name,Hobbies string
}
type Cat struct {
Name,FurColor string
}
func main() {
people := []Person{}
createThings(&people,10)
log.Println(people)
cats := []Cat{}
createThigns(&cats,5)
log.Println(cats)
}
func createThings(slice interface{},num int) {
b := strings.Replace(reflect.TypeOf(slice).String(),"*[]main.","",-1)
log.Println(b)
for c:=0;c<num;c++ {
eval("item := "+b+"{}")
*slice = append(*slice,item)
}
}
Essentially, the statement eval("item := "+b+"{}")
is what I would have done in other programming languages that allow it, but from what I understand, it's not something idomatic to golang.
I've seen something similar in the documentation for http://gorm.io where you can do something like this:
cats := []Cat{}
db.Find(&cats)
people :=[]Person{}
db.Find(&people)
The gorm object will add more records to cats
or people
even though they are completely different types. I had a hard time digging into the gorm code to see how they do this.
I wanted to know how I can change my createThings
function so that it can take a slice of anything, and then add more empty records to it. (Later, I'll use reflection to determine what fields are available in the structs, and populate with random data for the purposes of a game I'm making.)