How can I pass struct to function as parameter in go lang

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

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 get the error

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

      

have play.google.com violin address

+3


source to share


4 answers


You are looking for,

func test(class MyClass) {
    fmt.Println(class.Name)
}

      

At its core, a method recognizes class

as some kind of object that implements an empty interface (which means its scope and methods are completely unknown), so you get an error.



Another 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 in your example. This only makes sense if you are going to use a type switch or have multiple code paths that do different things based on the actual type class

.

+9


source


Depending on your needs, you have (at least) two options:

  • Method for structure type
  • Func, which takes a struct type as a parameter


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 can provide some front-end wizardry that I forgot about.

+3


source


Please see the Debug , Get methods . It uses user stuct with its methods. https://play.golang.org/p/E_WkLWGdeB

    package main

    import "fmt"

    // user defines a user in the program.
    type user struct {
        name  string
        email string
        status string
    }
    func debug(u user) {
         fmt.Printf("%+v\n", u)
    }   

    // notify implements a method with a value receiver.
    func (u user) notify() {
        fmt.Printf("User: Sending User Email To %s<%s>\n", u.name, u.email)
    }

    // changeEmail implements a method with a pointer receiver.
    func (u *user) changeEmail(email string) {
        u.email = email
    }

    func (u *user) changeName(name string) {
        u.name = name
    }

    func (u *user) Send() {
        u.notify()
    }

    // main is the entry point for the application.
    func main() {
        // Pointers of type user can also be used to methods
        // declared with a value receiver.
        john:= &user{"John", "john@exemple.com", "enabled"}

        john.changeName("John Smith")
        john.changeEmail("john@gmail.com")
        john.notify()

        Receive(john)

      

debug (user {"Willy", " Willy@exemple.com ", "enabled"})}

    func Receive(user interface{changeName(s string); changeEmail(s string); Send() }){
        user.changeName("Bill")
        user.changeEmail("bill@billy-exemple.com")
        user.Send()
    }

      

0


source


If you really want to send some kind of structure in a generic way as written in your original question (empty interface parameter) so that AnyStruct.SomeField and AnotherStruct.SomeField or AnyOtherStruct.AnyField can be accessed, AFAIK the reflecton functions go is the way to go ...

For example, if you look at a JSON marshal function, it takes almost any structure as a parameter ("v") sent to the function with an empty interface parameter. This marshal function then ends up calling

e.reflectValue(reflect.ValueOf(v), opts)

      

But you're probably looking for something as simple as the other answers have suggested, that doesn't need extended reflection (sort of a generic way of programming).

However, I post this answer in case other readers are interested in submitting structs at all, without needing to know what struct fields are.

The reason the JSON parser needs to share the structure is for the convenience of the user defining whatever structure he wants and then Go will automatically parse the structure and map it against the JSON syntax. You can imagine 100 different structural layouts that you just want to put in a text file without knowing all of their structural layouts beforehand - a function can define it at runtime, how the reflector works (other languages ​​call it runtime type information, metaprogramming, etc. etc.).

0


source







All Articles