go - How to use passed struct in function -


i saw somewhere, not remember where, slice struct passing through function 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 use here slice struct in function. have idea, how can use in function?

in order use slice struct (or other value stored in interface), must first type assertion or type switch:

type assertion:

func passslice(arg interface{}) {     // put args value in v if of type []struct{ name string }     v, ok := arg.([]struct{ name string })     if !ok {         // did not contain value of type []struct{name string}         return     }     _, s := range v {         fmt.println(s.name)     } } 

playground: http://play.golang.org/p/kifevc3vq_

type switches similar, can have cases multiple types.

there option of using reflect package, allowing more dynamically handle interface values without knowing before hand types can expect, using reflection more complex. know more using reflection in golang, can here:


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

jquery - Keeping Kendo Datepicker in min/max range -