dtvq4978 2014-09-23 23:49
浏览 7
已采纳

重新定义类型格式和方法

Here is a basic go program

package main

import (
        "fmt"
        "time"
)

type myTime time.Time

func main() {
        my := myTime(time.Now())
        fmt.Println(my)

        normal := time.Now()
        fmt.Println(normal)
}

And the corresponding output

{63547112172 291468455 0x545980}
2014-09-23 23:36:12.292132305 +0000 UTC

I would like to know why myTime prints diffrently than time.Time. They basically are supposed to be from the same type... Also, if I try to access any method of time.Time, let's say, Day, it's available for "normal" but not for "my".

Thanks!

  • 写回答

2条回答 默认 最新

  • dpxo13079 2014-09-24 00:01
    关注

    Your new type does not inherit methods from time.Time. To quote the spec:

    The declared type does not inherit any methods bound to the existing type

    Since there is no String method, it won't print a meaningful value. You need to implement that yourself.

    Your other option is to embed time.Time in your own type. That way you can include the functionality of time.Time but also add your own functionality.

    Playground link: http://play.golang.org/p/PY6LIBoP6H

    type myTime struct {
        time.Time
    }
    
    func (t myTime) String() string {
        return "<Custom format here>"
    }
    
    func main() {
        my := myTime{time.Now()}
        fmt.Println(my)
    
        normal := time.Now()
        fmt.Println(normal)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 求懂行的大ge给小di解答下!
  • ¥15 pcl运行在qt msvc2019环境运行效率低于visual studio 2019
  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活
  • ¥15 sqlserver中加密的密码字段查询问题
  • ¥20 有谁能看看我coe文件到底哪儿有问题吗?
  • ¥20 我的这个coe文件到底哪儿出问题了
  • ¥15 matlab使用自定义函数时一直报错输入参数过多
  • ¥15 设计一个温度闭环控制系统