Go语言爱好者周刊:第 74 期

polaris · · 8492 次点击
这道题属于坑题, 涉及到标准库Marshal函数和time.Time结构体的相关知识, 包括对time.Time结构的Marshal的知识. 下面是解析 ## 官方文档Marshal函数: >Marshal returns the JSON encoding of v. >Marshal traverses the value v recursively. If an encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce JSON. If no MarshalJSON method is present but **the value implements *encoding.TextMarshaler* instead, Marshal calls its *MarshalText* method and encodes the result as a JSON string**. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of UnmarshalJSON. >Otherwise, Marshal uses the following type-dependent default encodings >... ## 示例, t变量拥有TextMarshaler函数 ```go package main import ( "encoding" "fmt" "time" ) func main() { var t interface{} t = struct { time.Time N int }{ time.Date(2020, 12, 20, 0, 0, 0, 0, time.UTC), 5, } if tmj, ok := t.(encoding.TextMarshaler); ok { b, _ := tmj.MarshalText() fmt.Printf("type is identified as TextMarshaler, output is `%s`\n", b) } else { fmt.Println("t doesn't has MarshalText function") } } ``` [playground of above code](https://goplay.space/#gfVJEeKPrex)
#4
更多评论
实际答案是B,有没有大佬说一下为什么???
#1
fmt.Println(t) 问题出在结构体上,至于为啥,我也有点懵...
#2