为什么获取月份时,默认获取的格式为string

标准fmt中定义

// Stringer is implemented by any value that has a String method,
// which defines the ``native'' format for that value.
// The String method is used to print values passed as an operand
// to any format that accepts a string or to an unformatted printer
// such as Print.
type Stringer interface {
    String() string
}

任何对象定义了String方法,即可以Stringer 类型,fmt、log 进行print输出时会识别为Stringer类型,调用String 方法进行打印输出,即我们可以利用String来进行定制化输出。

// String returns the English name of the month ("January", "February", ...).
func (m Month1) String1() string {
	if January <= m && m <= December {
		return months1[m-1]
	}
	buf := make([]byte, 20)
	n := fmtInt(buf, uint64(m))
	return "%!Month(" + string(buf[n:]) + ")"
}

实例

对于结构体打印,直接调用Println,只能打印其值,如下。

package main

import (
    "log"
)

type test struct {
    X string
    Y int
}

func main() {
    a := test{X: "test", Y: 11}
    log.Println(a)
}

输入为

2019/03/20 13:04:06 {test 11}

现定义String方法,实现Marshal打印

package main

import (
    "encoding/json"
    "log"
)

type test struct {
    X string
    Y int
}

func (test test) String() string {
    out, err := json.Marshal(test)
    if err != nil {
        return err.Error()
    }
    return string(out)
}

func main() {
    a := test{X: "test", Y: 11}
    log.Println(a)
}

输出结果

2019/03/20 13:08:02 {"X":"test","Y":11}

标题:为什么获取月份时,默认获取的格式为string
作者:sun
地址:http://sunjuhui.top/articles/2019/07/22/1563788701809.html