来自 http://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go有一个例子说明了在 Go 中接口(interface)的可能使用。代码如下:
package main
import (
"encoding/json"
"fmt"
"reflect"
"time"
)
// start with a string representation of our JSON data
var input = `
{
"created_at": "Thu May 31 00:00:01 +0000 2012"
}
`
type Timestamp time.Time
func (t *Timestamp) UnmarshalJSON(b []byte) error {
v, err := time.Parse(time.RubyDate, string(b[1:len(b)-1]))
if err != nil {
return err
}
*t = Timestamp(v)
return nil
}
func main() {
// our target will be of type map[string]interface{}, which is a pretty generic type
// that will give us a hashtable whose keys are strings, and whose values are of
// type interface{}
var val map[string]Timestamp
if err := json.Unmarshal([]byte(input), &val); err != nil {
panic(err)
}
fmt.Println(val)
for k, v := range val {
fmt.Println(k, reflect.TypeOf(v))
}
fmt.Println(time.Time(val["created_at"]))
}
结果是这样的:
map[created_at:{63474019201 0 0x59f680}]
created_at main.Timestamp
2012-05-31 00:00:01 +0000 UTC
我很难理解函数是如何调用的
json.Unmarshal([]byte(input), &val){...}
与前面定义的方法有关
func (t *Timestamp) UnmarshalJSON(b []byte) error{...}
在 http://golang.org/pkg/encoding/json/#Unmarshal 阅读文档更让我困惑。
我显然在这里遗漏了一些东西,但我想不通。
最佳答案
在 Go 中,接口(interface)仅通过实现其方法来实现。它与大多数其他流行语言(Java、C#、C++)有很大不同,在这些语言中,类接口(interface)应在类声明中明确提及。
有关此概念的详细说明,您可以在 Go 文档中找到:https://golang.org/doc/effective_go.html#interfaces
所以 func (t *Timestamp) UnmarshalJSON(...)
定义了一个方法,同时实现了接口(interface)。 json.Unmarshal
然后将 val
的元素类型断言到 Unmarshaler
接口(interface) ( http://golang.org/pkg/encoding/json/#Unmarshaler ) 并调用 UnmarshalJSON
方法从字节 slice 构造它们。
关于json - 有人可以用 Go 解释这个接口(interface)示例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26035172/