【发布时间】:2014-02-16 02:25:12
【问题描述】:
我目前正在阅读https://github.com/codegangsta/inject go 包的源代码,以了解该包是如何工作的。
我对 https://github.com/codegangsta/inject/blob/master/inject.go 文件有一些疑问,该文件使用了我不理解的 Go 语言的某些元素,并且在文档中找不到准确的解释。
// InterfaceOf dereferences a pointer to an Interface type.
// It panics if value is not an pointer to an interface.
func InterfaceOf(value interface{}) reflect.Type {
t := reflect.TypeOf(value)
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Interface {
panic("Called inject.InterfaceOf with a value that is not a pointer to an interface. (*MyInterface)(nil)")
}
return t
}
我的第一个问题是关于for 循环。为什么它使用带有测试表达式的 for 循环?
第二个与恐慌函数中的消息有关。 (*MyInterface)(nil) 提到了“指向接口的指针”。当您检查类型是否实现结构时,我只会在 go 文档中遇到有关“编译时检查结构”的类似结构:
var _ SomeType = (*SomeInterface)(nil)
我没有找到关于带有(*Interface)(nil) 和接口指针的语句的任何信息。
我们应该如何解释这句话?与指向接口的指针有什么关系,我在哪里可以找到有关指向接口的指针的信息?
【问题讨论】:
-
其他语言中的for与while循环相同
-
好的!我对第一个问题太愚蠢了:p 对于第二个问题,你有像第一个问题一样清楚的解释吗?
-
它是一种转换语法。所以将 nil 转换为 *MyInterface
标签: go