英文:
Append Interface Element Into Interface Golang
问题
我有一个接受所有类型结构体作为接口的函数。如果我尝试打印 s.Index(i)
,它会给我返回值。然而,一旦我将其附加到 allRows []interface{}
中并打印出来,我得到的是我传递给函数的结构体类型,而不是值。举个例子:
fmt.Println("AllRows", allRows)
[<adminPanel.allBeaconInfo Value> <adminPanel.allBeaconInfo Value>
<adminPanel.allBeaconInfo Value> <adminPanel.allBeaconInfo Value>
<adminPanel.allBeaconInfo Value>]
func pagination(c *gin.Context, st interface{}) {
var allRows []interface{}
switch reflect.TypeOf(st).Kind() {
case reflect.Slice:
s := reflect.ValueOf(st)
for i := 0; i < s.Len(); i++ {
allRows = append(allRows, s.Index(i))
fmt.Println(allRows)
}
}
fmt.Println("AllRows", allRows)
}
请注意,这是你提供的代码,我只是将其翻译成了中文。
英文:
I have a function which accept all type of struct as interface. If I try to print
> s.Index(i)
It gives me the values. However once I append it into
> allRows []interface{}
and print it out. Instead of value I am getting the type of struct that I passed the function.
As an exapmle.
> fmt.Println("AllRows",allRows)
>
> [<adminPanel.allBeaconInfo Value> <adminPanel.allBeaconInfo Value>
> <adminPanel.allBeaconInfo Value> <adminPanel.allBeaconInfo Value>
> <adminPanel.allBeaconInfo Value>]
func pagination(c *gin.Context, st interface{}) {
var allRows []interface{}
switch reflect.TypeOf(st).Kind() {
case reflect.Slice:
s := reflect.ValueOf(st)
for i := 0; i < s.Len(); i++ {
allRows=append(allRows,s.Index(i))
fmt.Println(allRows)
}
}
fmt.Println("AllRows",allRows)
答案1
得分: 0
表达式s.Index(i)
评估为包含实际切片元素的reflect.Value
。调用Value.Interface()以获取实际切片元素。
var allRows []interface{}
switch reflect.TypeOf(st).Kind() {
case reflect.Slice:
s := reflect.ValueOf(st)
for i := 0; i < s.Len(); i++ {
allRows = append(allRows, s.Index(i).Interface())
fmt.Println(allRows)
}
}
英文:
The expression s.Index(i)
evaluates to a reflect.Value
containing the actual slice element. Call Value.Interface() to get the actual slice element.
var allRows []interface{}
switch reflect.TypeOf(st).Kind() {
case reflect.Slice:
s := reflect.ValueOf(st)
for i := 0; i < s.Len(); i++ {
allRows=append(allRows,s.Index(i).Interface())
fmt.Println(allRows)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论