关注点:go语言的语法技巧
一、问题
看tendermint源码的时候,会经常看见类似下面的代码
var _ types.Application = (*PersistentKVStoreApplication)(nil)
从语义上来说,这句代码的作用强制转换一个空指针到一个unused的变量。这样看来,完全是没什么卵用,那为什么还出现在多个文件里呢?百思不得其解
刚开始不懂,后来慢慢想,猜测是肯定是和编译器相关。
今天浏览后缀是pb.go的源文件时,也发现很多类似的代码
const _ = proto.GoGoProtoPackageIsVersion2
幸运的是,这里有一些注释来解释这个事情
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
再去网上查就比较容易了,下面是在Google中搜索到的内容
This post is about a little-known way to make compile-time assertions in Go. You probably shouldn’t use it, but it is interesting to know about.
As a warm-up, here’s a fairly well-known form of compile-time assertions in Go: Interface satisfaction checks.
In this code (playground), the
var _ =
line ensures that typeW
is astringWriter
, as checked for byio.WriteString
.
详情请查看原文