dtvdz911959 2017-07-17 09:02
浏览 49
已采纳

动态结构作为参数Golang

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)
}
  • 写回答

1条回答 默认 最新

  • dsqpx86002 2017-07-17 09:50
    关注

    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
    ", 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于php中URL传递GET全局变量的问题
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件