To convert a slice of custom structs to a slice of interface values in Golang, you can use a for loop to iterate through the source slice and individually convert each struct to an interface value. Here's an example:
package main
import "fmt"
type MyStruct struct {
Name string
Age int
}
func main() {
// Create a slice of custom structs
structs := []MyStruct{
{Name: "John", Age: 29},
{Name: "Jane", Age: 34},
}
// Create a slice of interface values
values := make([]interface{}, len(structs))
// Convert each struct to an interface value
for i, s := range structs {
values[i] = s
}
// Print the interface values
for _, v := range values {
fmt.Println(v)
}
}
Output:
{John 29}
{Jane 34}
In this example, we first define a custom struct MyStruct
with two fields: Name
and Age
. We then create a slice of MyStruct
values and populate it with some data.
Next, we create a new slice values
of interface values using the make
function, specifying the length corresponding to the number of structs in the original slice.
Finally, we iterate through the original slice of structs and assign each struct to the corresponding index in the interface value slice. This works because in Go, an interface value can hold any value with methods matching the interface signature.
You can then use the resulting slice of interface values as needed.