猿问

将接口元素附加到接口 Golang

我有一个函数可以接受所有类型的结构作为接口。如果我尝试打印

s.Index(i)

它给了我价值观。但是,一旦我将其附加到

allRows []接口{}

并打印出来。我得到的不是值,而是我传递函数的结构类型。例如。

fmt.Println("AllRows",allRows)

[<adminPanel.allBeaconInfo 值> <adminPanel.allBeaconInfo 值> <adminPanel.allBeaconInfo 值> <adminPanel.allBeaconInfo 值> <adminPanel.allBeaconInfo 值>]

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)


慕田峪9158850
浏览 87回答 1
1回答

江户川乱折腾

表达式s.Index(i)计算为reflect.Value包含实际切片元素的 a。调用Value.Interface()以获取实际的切片元素。&nbsp; &nbsp; var allRows []interface{}&nbsp; &nbsp; &nbsp; &nbsp; switch reflect.TypeOf(st).Kind() {&nbsp; &nbsp; &nbsp; &nbsp; case reflect.Slice:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s := reflect.ValueOf(st)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < s.Len(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; allRows=append(allRows,s.Index(i).Interface())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(allRows)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Go
我要回答