Reputation: 77
In my func I have a variable of Product struct but I have not access to Product struct and I want make a slice of Product from it's variable for example:
test1 := Product{}
....
....
....
test2 := []TypeOf(test1)
how can I do that?
Update: what I want to actually achieve?
I have some structs that want to use in a adapter for gorm.
In my adapter for example I have a FindAll method that need slice of one of my struct.
All my structs is in a package named Domains and I don't want send needed variable from where use(call) FindAll function.
Now I registered all my structs to a Map and fetch them in adapter with struct name but the result is a variable of that struct not type of that struct so I can't make another variable from it or make a slice of that.
Upvotes: 0
Views: 227
Reputation: 30
You want slice of Product with test1 element?
package main
import "fmt"
type Product struct{
Price float64
}
func main() {
test1 := Product{Price: 1.00}
test2 := []Product{test1}
fmt.Println(test2)
}
Upvotes: 0
Reputation: 46413
You can do this using reflection, in particular TypeOf
, SliceOf
, and MakeSlice
, however, it won't be very useful because you can only get a reference to it as an interface{}
, which you can't use like a slice. Alternatively, you could assign it to a slice of type []interface{}
, which would let you work with the slice, but again, without being able to reference the underlying type, you can't really do anything with the values. You might need to reconsider your design.
Upvotes: 2