how can i pass struct to function as parameter in go lang -


how can pass struct function parameter in go lang

there code;

package main  import (     "fmt" )  type myclass struct {     name string }  func test(class interface{}) {     fmt.println(class.name) }  func main() {      test(myclass{name: "jhon"}) } 

when run it, getting error this

# command-line-arguments /tmp/sandbox290239038/main.go:12: class.name undefined (type interface {} has no field or method name) 

there play.google.com fiddle address

you're looking for;

func test(class myclass) {     fmt.println(class.name) } 

as stands method recognizes class object implements empty interface (meaning in scope it's fields , methods unknown) why error.

your other option this;

func test(class interface{}) {      if c, ok := class.(myclass); ok { // type assert on              fmt.println(c.name)      } } 

but there no reason in example. makes sense if you're going type switch or have multiple code paths different things based on actual type of class.


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -