V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
guonaihong
V2EX  ›  程序员

golang 实现 rust assert_eq!断言

  •  
  •   guonaihong ·
    guonaihong · 2019-10-29 09:07:09 +08:00 · 1621 次点击
    这是一个创建于 1631 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近实在受不了诱惑,撸了把 rust,发现这里面还是有很多用起来很爽的东西,寻思着有些可以移植到 go 里面。

    rust assert_xxx 断言

    • cargo new --bin assert(这个命令创建工程)
    • 编辑如下代码
    fn main() {
        let x = 3;
        assert_eq!(x, 1); 
    }
    
    
    • cargo run (运行)
    • 输出
    thread 'main' panicked at 'assertion failed: `(left == right)`
      left: `3`,
     right: `1`', src/main.rs:3:5
    note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
    
    

    go 实现 assert_eq 断言

    • mkidr assert (创建工作目录)
    • cd assert && go mod init main (创建 go mod)
    • 编辑如下代码
    package main
    
    import (
        "fmt"
        "github.com/stretchr/testify/assert"
    )
    
    type errorf func(format string, a ...interface{}) (n int, err error)
    
    func (e errorf) Errorf(format string, args ...interface{}) {
        e(format, args...)
    }
    
    //Errorf(format string, args ...interface{})
    
    func main() {
        x := 3
        assert.Equal(errorf(fmt.Printf), x, 1)
    }
    
    
    • go run assert.go (运行)
    • 输出
    
    	Error Trace:	assert.go:18
    	            				proc.go:203
    	            				asm_amd64.s:1357
    	Error:      	Not equal: 
    	            	expected: 3
    	            	actual  : 1
    
    

    实现说明

    "github.com/stretchr/testify/assert" 本来是给*testing.T 用的,如果要在 main 里面使用,就需要实现他的接口。这里面给函数定义函数,体现了 go 里面只要是类型就可以挂载函数,函数也不例外。
    该技巧的作用是用函数指针实现某个接口。 (实用性很高)

    github

    https://github.com/guonaihong/gout

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3968 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:30 · PVG 18:30 · LAX 03:30 · JFK 06:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.