0

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.

2 Answers2

2

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.

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • Thank you @Adrian I had already tried all of them! and as you said with no good result. I think should describe my use case and discuss about new approach. – Mehrdad Dadkhah Aug 02 '17 at 07:34
0

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)
}
eXMooR
  • 30
  • 1
  • 1
  • Question states "I have not access to Product struct", which I believe means they can't reference it - i.e. they cannot just create a `[]Product`. But maybe the asker can explain. – Adrian Aug 01 '17 at 21:07
  • @eXMooR @Adrian Yes, I have no straight access to Product type so I can't use: ``` test2 := []Product{} ``` – Mehrdad Dadkhah Aug 02 '17 at 07:29