dongpo0409 2015-03-29 14:21
浏览 30
已采纳

Golang一起调用方法的最有效方法

im looking for the most efficient way to invoke couple of method together.

Basically what im trying to to is invoke those method together and if something went wrong return error else return the struct Type.

This code is working but i can't get the struct type or error and im not sure if its the correct way.

go func()(struct,err) {
        struct,err= sm.MethodA()//return struct type or error
         err = sm.MethodB()//return error or nill
return struct,err
    }()
  • 写回答

1条回答 默认 最新

  • dsfsdfsdfsdfsdf45454 2015-03-29 18:07
    关注

    In Go, it's idiomatic to return the two values and check for nil against the error

    For example:

    func myFunc(sm SomeStruct) (MyStruct, error) {
      s, err := sm.MethodA()
      if err != nil {
        return nil, err
      }
      if err := sm.MethodB(); err != nil {
        return nil, err
      }
    
      return s, nil 
    }
    

    One thing to note, is that you're running your function in a goroutine. Any return value inside that goroutine won't be returned to your main goroutine.

    In order to get the return values for that go routine you must use channels that will wait for the values.

    In your case

    errChan := make(chan error)
    retChan := make(chan SomeStructType)
    
    go func() {
        myVal, err := sm.MethodA()
        if err != nil {
            errChan <- err
            return
        }
    
        if err := sm.MethodB(); err != nil {
            errChan <- err
            return
        }
    
        retChan <- myVal
    }()
    
    select {
    case err := <-errChan:
        fmt.Println(err)
    case val := <-retChan:
        fmt.Printf("My value: %v
    ", val)
    }
    

    You can mess around with it here to make more sense out of it:

    http://play.golang.org/p/TtfFIZerhk

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

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址