Home >Backend Development >Golang >How Can I Call time.Time Methods on a Custom Type in Go?

How Can I Call time.Time Methods on a Custom Type in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 10:24:15456browse

How Can I Call time.Time Methods on a Custom Type in Go?

Calling Method of Named Type

You have created a named type, StartTime, which is a wrapper around a time.Time for JSON unmarshalling. However, you are unable to call methods of time.Time, such as Date(), on your StartTime instance.

This is because, by using the type keyword, you have effectively created a new type, rather than extending the existing time.Time type. To preserve the original methods while adding your own, you should use type embedding:

type StartTime struct {
    time.Time
}

With embedding, the fields and methods of the embedded type (time.Time in this case) are "promoted" and can be accessed on the named type (StartTime). Thus, you can now call myStartTime.Date().

Here's an example:

package main

import (
    "fmt"
    "time"
)

type StartTime struct {
    time.Time
}

func main() {
    s := StartTime{time.Now()}
    fmt.Println(s.Date())
}

Output:

2009 November 10

The above is the detailed content of How Can I Call time.Time Methods on a Custom Type in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn