Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic struct as parameter Golang

Tags:

go

I'm wondering whether it is possible to pass a dynamic struct as function's parameter ?

type ReturnValue struct {
   Status string
   CustomStruct // here should store any struct given
} 

func GetReturn(status string, class interface{}){
   var result = ReturnValue {Status : status, CustomStruct : //here any struct should be stored}

   fmt.Prinln(result)
}

type Message1 struct {
   message : string
}

func main(){
   var message = Message1 {message: "Hello"}
   GetReturn("success",  message)
}
like image 367
Angger Avatar asked Jul 17 '17 09:07

Angger


1 Answers

You could use an interface like this and an if statement to get it back to whatever struct it orginated as tho.

import (
    "fmt"
)

type ReturnValue struct {
   Status string
   CustomStruct interface{}
} 

func GetReturn(status string, class interface{}){
   var result = ReturnValue {Status : status, CustomStruct: class}

   fmt.Println(result)

   msg, ok := result.CustomStruct.(Message1)
   if ok {
      fmt.Printf("Message1 is %s\n", msg.message)
   }
}

type Message1 struct {
   message string
}

type Message2 struct {
   message string
}

func main(){
   var m1 = Message1 {message: "Hello1"}
   GetReturn("success",  m1)

   var m2 = Message2 {message: "Hello2"}
   GetReturn("success",  m2)
}

https://play.golang.org/p/L6VYV80x27

like image 147
Kent Avatar answered Sep 23 '22 08:09

Kent