将接口元素添加到Golang接口中

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

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 &lt; s.Len(); i++ {
        			allRows=append(allRows,s.Index(i))
        			fmt.Println(allRows)
        		}
        	}
        
        	fmt.Println(&quot;AllRows&quot;,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 &lt; s.Len(); i++ {
                allRows=append(allRows,s.Index(i).Interface())
                fmt.Println(allRows)
            }
        }

huangapple
  • 本文由 发表于 2021年11月10日 02:26:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/69903254.html
匿名

发表评论

匿名网友

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

确定