golang接口遵循编译类型检查

huangapple go评论84阅读模式
英文:

golang interface compliance compile type check

问题

我从camlistore(http://code.google.com/p/camlistore/source/browse/pkg/cacher/cacher.go)中看到以下语句。

var (
        _ blobref.StreamingFetcher = (*CachingFetcher)(nil)
        _ blobref.SeekFetcher      = (*CachingFetcher)(nil)
        _ blobref.StreamingFetcher = (*DiskCache)(nil)
        _ blobref.SeekFetcher      = (*DiskCache)(nil)
)

我理解这些语句没有创建变量,而是确保编译器检查CachingFetcher是否实现了StreamingFetcher和SeekFetcher的公共函数。RHS部分使用了一个带有nil参数的指针构造语法。在Go语言中,这种语法表示什么意思?

英文:

I see the following statements from camlistore(http://code.google.com/p/camlistore/source/browse/pkg/cacher/cacher.go).

var (
        _ blobref.StreamingFetcher = (*CachingFetcher)(nil)
        _ blobref.SeekFetcher      = (*CachingFetcher)(nil)
        _ blobref.StreamingFetcher = (*DiskCache)(nil)
        _ blobref.SeekFetcher      = (*DiskCache)(nil)
)

I understand that no variables are created and the statements ensure compiler checks that CachingFether implements public functions of StreamingFetcher and SeekFetcher. RHS portion uses a pointer constructor syntax with a nil parameter. What does this syntax mean in Go language ?

答案1

得分: 18

(*T)(nil) 是一个转换。在这种情况下,它代表一个有类型的nil,即在赋值之前与例如

var p *T

相同的值。

转换的标准语法是T(expr),但是*的优先级会导致它在

*T(expr)

中被错误地绑定。这个语法表示对函数T的返回值进行解引用,参数为expr。这就是为什么转换有一种替代语法的原因:

(T)(expr)

其中T当然可以是*U。因此

(*U)(expr)

是你在Camlistore存储库中看到的形式的广义形式。

英文:

(*T)(nil) is a Conversion. In this case it stands for a typed nil, ie. the same value which, for example

var p *T

has before assigning anything to it.

The standard syntax of a conversion is T(expr), but the priority of the * would bind it wrongly in

*T(expr)

This syntax means dereferencing the return value of function T with one argument expr. That's why the conversion has an alternative syntax:

(T)(expr)

where T can of course be *U. Therefore

(*U)(expr)

is the generalized form of what you see in the Camlistore repository.

huangapple
  • 本文由 发表于 2013年8月1日 20:47:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/17994519.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定