donglu1472 2014-09-20 16:07
浏览 186
已采纳

使go变量接受多种类型

I would like to develop a library in Go which makes use of the different file formats of the debug package in the go standard packages (http://golang.org/pkg/debug/). The idea is to open a file and print out information about that file. Now I would like to automatically recognize the correct file format by testing all relevant file types. For instance, to test if a file is a simple Mach-O or a fat Mach-O file, I am trying to open the file with both Open methods:

  file, err := macho.Open(filename)
  if err != nil {
      fmt.Println("Not an Mach-O file.")
  }
  file, err = macho.OpenFat(filename)
  if err != nil {
      fmt.Println("Not an fat Mach-O file. Exiting.")
      return
  } 

Unfortunately the file variable is (of course) type checked, and I get the following error:

cannot assign *macho.FatFile to file (type *macho.File) in multiple assignment

I am not even sure of this is the correct way of approaching this. Can anyone point me to the right direction how to perfom this properly?

  • 写回答

2条回答 默认 最新

  • dook0034 2014-09-20 18:08
    关注

    Or don't even declare file at all, if you're not going to do anything with it.

    if _, err := macho.Open(filename); err != nil {
        fmt.Println("Not an Mach-O file.")
    }
    if _, err = macho.OpenFat(filename); err != nil {
        fmt.Println("Not an fat Mach-O file. Exiting.")
        return
    } 
    

    If you actually wanted to call some function on File, then you could declare it of an interface type with the func(s) you want to call, then you could say something like:

    var file io.Closer
    file, err := macho.Open(filename)
    if err != nil {
        fmt.Println("Not an Mach-O file.")
    }
    file, err = macho.OpenFat(filename)
    if err != nil {
        fmt.Println("Not an fat Mach-O file. Exiting.")
        return
    }
    file.Close()
    

    In this case it't not that interesting because it looks like macho.File and macho.FatFile's only common function is Close()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测