Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Append Interface Element Into Interface Golang

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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)
            }
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading