-3

I saw somewhere, but I do not remember where, that a slice struct is passing through function like the following code snippet.

package main

import "fmt"

func passSlice(arg interface{}) {
    fmt.Println(arg)
}

func main() {

    res := []struct {
        Name string
    }{}

    passSlice(res)

}

I have no idea, how to use here a slice struct in the function. Have someone a idea, how can I use it in the function?

softshipper
  • 32,463
  • 51
  • 192
  • 400
  • 1
    Good starting point: http://stackoverflow.com/a/12754757/6309 – VonC Sep 09 '14 at 18:53
  • 1
    Why don't you work yourself through the Go tour and Effective Go, both available on golang.org? – Volker Sep 09 '14 at 19:06
  • possible duplicate of [Type converting slices of interfaces in go](http://stackoverflow.com/questions/12753805/type-converting-slices-of-interfaces-in-go) – OneOfOne Sep 09 '14 at 21:47

1 Answers1

2

In order to use the slice struct (or any other value stored in an interface), you must first do a type assertion or type switch:

Type assertion:

func passSlice(arg interface{}) {
    // Put args value in v if it is of type []struct{ Name string }
    v, ok := arg.([]struct{ Name string })
    if !ok {
        // did not contain a value of type []struct{Name string}
        return
    }
    for _, s := range v {
        fmt.Println(s.Name)
    }
}

Playground: http://play.golang.org/p/KiFeVC3VQ_

Type switches are similar, but can have cases for multiple types.

There is also an option of using the reflect package, allowing you to more dynamically handle interface values without knowing before hand what types you can expect, but using reflection is also more complex. To know more about using reflection in Golang, you can look here:

ANisus
  • 74,460
  • 29
  • 162
  • 158
  • Remembering too that you can "one-line" that assertion to `v, ok := arg.([]struct{ Name string }); !ok { return }`.. with the braces in the right spots (couldn't do it in comments). – Simon Whitehead Sep 10 '14 at 01:40