使用结构体的变量创建一个切片。

huangapple go评论161阅读模式
英文:

Make slice of a struct with a variable of it

问题

在我的函数中,我有一个Product结构体的变量,但我无法访问Product结构体,我想从它的变量中创建一个Product的切片,例如:

test1 := Product{}

....
....
....

test2 := []TypeOf(test1)

我该如何做到这一点?

更新
我实际上想要实现什么?

我有一些结构体,想在gorm的适配器中使用。

在我的适配器中,例如,我有一个FindAll方法,需要一个我结构体的切片。

所有我的结构体都在一个名为Domains的包中,我不想从使用(调用)FindAll函数的地方发送所需的变量。

现在,我将所有的结构体都注册到一个Map中,并在适配器中使用结构体名称获取它们,但结果是该结构体的变量,而不是该结构体的类型,所以我无法从中创建另一个变量或者创建该结构体的切片。

英文:

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.

答案1

得分: 2

你可以使用reflection来实现这个,特别是使用TypeOfSliceOfMakeSlice函数。然而,这种方法可能不太有用,因为你只能将其作为interface{}类型的引用获取,而不能像使用切片那样使用它。另一种方法是将其赋值给类型为[]interface{}的切片,这样可以使用切片,但是由于无法引用底层类型,你实际上不能对值进行任何操作。你可能需要重新考虑你的设计。

英文:

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.

答案2

得分: 0

你想要使用test1元素对Product进行切片吗?

package main

import "fmt"

type Product struct{
    Price float64
}

func main() {
   test1 := Product{Price: 1.00}

   test2 := []Product{test1}
   fmt.Println(test2)
}
英文:

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)
}

huangapple
  • 本文由 发表于 2017年8月2日 04:56:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/45447571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定