看到过好几次别人的代码里面都有全局的匿名变量,比如这里:
...
type cachedWriter struct {
	gin.ResponseWriter
	status  int
	written bool
	store   persistence.CacheStore
	expire  time.Duration
	key     string
}
var _ gin.ResponseWriter = &cachedWriter{}
...
代码地址:https://github.com/gin-contrib/cache/blob/master/cache.go#L45
这里 var _ gin.ResponseWriter = &cachedWriter{} 这样写是为了啥,没看明白,求赐教~
|      1imgk      2020-09-10 20:50:19 +08:00 via iPhone  6 确定 cacheWriter 实现接口 | 
|  |      2zengming00      2020-09-10 20:58:04 +08:00 ```go type myInterface interface { foo() } type myData struct{} func (o *myData) foo() { } var _ myInterface = &myData{} ``` 1 楼说得对,如果没有实现 myInterface 接口,那么在编译阶段就会报错 | 
|  |      3iCD OP 原来如此,我学会了! | 
|      4useben      2020-09-11 10:44:00 +08:00 在挺多开源框架见到, 确实技巧了. 不过用 goland 的话, 可以一键某结构实现某接口, 可以避免这样的检验了 | 
|  |      5weakish      2020-09-11 11:54:33 +08:00  1 golang FAQ 里有写: https://golang.org/doc/faq#guarantee_satisfies_interface | 
|      6githubhaoliu      2020-09-11 13:32:26 +08:00 还有一些是为了跳过 unused 检测,比如 var _ = xxx | 
|  |      7buzz2d0      2020-09-11 14:23:19 +08:00 学习了 | 
|      8securityCoding      2020-09-12 12:04:45 +08:00 学习了 | 
|  |      9schwarzeni00      2020-09-15 11:28:27 +08:00 我刚想发个新帖子问这个问题的,就看到这个帖子了。在看 client-go 源码的时候也看到这种用法了 ```go var _ RateLimiter = &ItemFastSlowRateLimiter{} ``` |