dongtan2603 2016-03-18 18:18
浏览 21
已采纳

比较Go中的错误

In my test file, I am trying to compare an actual error detected with the expected error. However, this comparison evaluates to false, and I'm unsure why. This even happens when I create two identical errors and compare them.

Code snippet:

func TestCompareErrors(t *testing.T) {
    if fmt.Errorf("Test Error") != fmt.Errorf("Test Error") {
        t.Errorf("Test failed")
    }
}

This results in "Test failed"

  • 写回答

2条回答 默认 最新

  • doulu4534 2016-03-18 18:22
    关注

    You are comparing two different values which happen to have the same error message. You want to compare predefined error values, just like you would with common values like io.EOF.

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

    var errTest = fmt.Errorf("test error")
    
    func do() error {
        return errTest
    }
    
    func main() {
        err := do()
        if err == errTest {
            log.Fatal("received error: ", err)
        }
    
    }
    

    You can read "Errors are Values" for a more in-depth explanation.

    If you need to provide more information with the error, you can create your own error type. You can then attach whatever information you want to the error, and check for that type of error via a type assertion.

    type myError string
    
    func (e myError) Error() string {
        return string(e)
    }
    
    func do() error {
        return myError("oops")
    }
    
    func main() {
        err := do()
        if err, ok := err.(myError); ok {
            log.Fatal("received myError: ", err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 复现论文:matlab仿真代码编写
  • ¥15 esp32驱动GC9A01循环播放视频
  • ¥15 惠普360g9的最新bios
  • ¥30 这个功能用什么软件发合适?
  • ¥60 微信小程序,取消订单,偶尔订单没有改变状态
  • ¥15 用pytorch实现PPO算法
  • ¥15 关于调制信号的星座图?
  • ¥30 前端传参时,后端接收不到参数
  • ¥15 这是有什么问题吗,我检查许可证了但是显示有呢
  • ¥15 机器学习预测遇到的目标函数问题