How can I pass a struct to function as a parameter in golang? There is my 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 I run it, I am getting an error like this
# command-line-arguments /tmp/sandbox290239038/main.go:12: class.Name undefined (type interface {} has no field or method Name)
there is play.golang.org fiddle address.
Structs can be passed as parameters by reference or by value. The default behavior is to pass Struct parameters by reference in partner operations and entries, and to pass them by value in public operations, but it is possible to override this behavior when declaring the parameters.
Structures can also be passed as parameters to the functions. When a function is called, if we pass the values of the variables to the function, it is known as the call by value. Instead of passing the values, if we pass the address of the variables to the function, it is known as call by reference.
Passing of structure to the function can be done in two ways: By passing all the elements to the function individually. By passing the entire structure to the function.
That means that the function will receive a COPY OF the struct, and that copy is what is manipulated from within the function. All field values in the copy will have the exact same values as the field values of the original struct - but the original struct and the copy occupy different locations in memory.
You're looking for;
func test(class MyClass) { fmt.Println(class.Name) }
As it stands the method recognizes class
as some object which implements the empty interface (meaning in that scope it's fields and methods are completely unknown) which is why you get the error.
Your other option is something like this;
func test(class interface{}) { if c, ok := class.(MyClass); ok { // type assert on it fmt.Println(c.Name) } }
But there is no reason to in your example. It only makes sense if you're going to do a type switch or have multiple code paths that do different things based on the actual type of class
.
Depending on your needs, you have (at least) two options:
package main import "fmt" type MyClass struct { Name string } func main() { cls := MyClass{Name: "Jhon"} // Both calls below produce same result cls.StructMethod() // "Jhon" FuncPassStruct(cls) // "Jhon" } // Method on struct type func (class MyClass) StructMethod() { fmt.Println(class.Name) } // Function that takes struct type as the parameter func FuncPassStruct(class MyClass) { fmt.Println(class.Name) }
I'm sure others may provide some interface wizardry I'm forgetting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With