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
Release: 2024-12-18 10:24:15
Original
461 people have browsed it

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
}
Copy after login

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())
}
Copy after login

Output:

2009 November 10
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template