有人可以在Go中解释这个界面示例吗?

时间:2014-09-25 09:34:50

标签: json interface go

来自http://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go的示例说明了Go中可能使用的接口。代码如下:

  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阅读文档让我更加困惑。

我显然在这里遗漏了一些东西,但我无法弄清楚。

1 个答案:

答案 0 :(得分:3)

在Go中,只需实现其方法即可实现接口。它与大多数其他流行语言(Java,C#,C ++)有很大的不同,其中类接口应该在类声明中明确提到。

您可以在Go文档中找到此概念的详细说明:https://golang.org/doc/effective_go.html#interfaces

因此func (t *Timestamp) UnmarshalJSON(...)定义了一个方法,同时实现了接口。然后json.Unmarshal类型将val的元素断言到Unmarshaler接口(http://golang.org/pkg/encoding/json/#Unmarshaler)并调用UnmarshalJSON方法从字节切片构造它们。 / p>

相关问题