golang 实现 rust assert_eq!断言

2019-10-29 09:07:09 +08:00
 guonaihong

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

rust assert_xxx 断言

fn main() {
    let x = 3;
    assert_eq!(x, 1); 
}

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 断言

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)
}


	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

1627 次点击
所在节点    程序员
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/613878

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX