最近实在受不了诱惑,撸了把 rust,发现这里面还是有很多用起来很爽的东西,寻思着有些可以移植到 go 里面。
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.
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 里面只要是类型就可以挂载函数,函数也不例外。
该技巧的作用是用函数指针实现某个接口。 (实用性很高)