go:underscore and interface name after the var keyword :var _ ... = ... meanming

Golang接口实现检查
本文解释了在Golang中使用var _ = T{}

https://stackoverflow.com/questions/30367803/why-declare-like-var-i-t-and-var-i-t-continuously-in-golang

Why declare like “var _ I = T{}” and “var _ I = &T{}” continuously in golang?

Ask Question

up vote 4 down vote favorite

1

When I read a copy of the docker/distribution source code, I find there are variables declared which make me quite confused. The code is:

var _ FileInfo = FileInfoInternal{}
var _ FileInfo = &FileInfoInternal{}

I don't know what the declare mean, and hope to get some help.

go registry docker

shareimprove this question

edited May 21 '15 at 16:27

Dave C

5,40322644

asked May 21 '15 at 7:56

JCheng

264

add a comment

2 Answers

active oldest votes

up vote 13 down vote accepted

From the FAQ:

You can ask the compiler to check that the type T implements the interface I by attempting an assignment:

type T struct{} 
var _ I = T{}   // Verify that T implements I.

In this case the blank identifier _ stands for the variable name which is not needed here (and thus prevents a "declared but not used" error).

And more general from the spec:

The blank identifier provides a way to ignore right-hand side values in an assignment:

_ = x       // evaluate x but ignore it 
x, _ = f()  // evaluate f() but ignore second result value

By testing both FileInfoInternal{} and &FileInfoInternal{} you check if the interface is implemented with a value receiver. A value receiver will accept both a value and a pointer whereas the pointer receiver will only work with a pointer and the first assignment by value will fail.

The second test with &FileInfoInternal{} is not actually needed (as confirmed by the author in the comments) since the first test will pass with a value receiver and fail with a pointer received. Thus the second test is redundant.

This is an excellent article that explains the difference between value and pointer receivers and how they are used very well.

shareimprove this answer

edited May 22 '15 at 8:15

answered May 21 '15 at 8:04

IamNaN

3,45021636

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值