英文:
Go - function returns datetime
问题
我正在学习Go语言,尝试创建一个返回日期时间的函数。
我已经编写了一个可以工作的代码(在线查看play.golang.org):
package main
import (
    "fmt"
    "time"
)
func getDatetime() time.Time {
    return time.Now()
}
func main() {
    fmt.Println(getDatetime())
}
但是!我真的不知道这是否正确。我对getDatetime函数的返回类型(time.Time)有疑问。它应该是字符串还是其他类型?
顺便说一下:对于这个简单的问题,我很抱歉,我是一个Python开发者,已经有几年了。
英文:
I'm learning go language and I try create a function returns datetime.
Already I've code that works (look online at play.golang.org):
package main
import (
    "fmt"
    "time"
)
func getDatetime() time.Time {
    return time.Now()
}
func main() {
    fmt.Println(getDatetime())
}
But! I really don't know is it correct. My doubt is about type of a return of a getDatetime function (time.Time). Should it be string or something else?
Btw: sorry for simple question, I'm python developer since few years.
答案1
得分: 3
除非函数的调用者期望返回一个字符串(比如 UI)并且打算对返回值进行字符串操作(在日期时间的上下文中这没有太多意义),否则你应该直接返回 time.Time。否则,调用者将无法使用提供的与时间相关的函数,如 time.After()、time.Before()、time.Equal() 等。
英文:
Unless the caller of your function is expecting a string (like a UI) and intending to do string manipulation on returned value (which doesn't make much sense in the context of datetime), you should just return time.Time. Otherwise, your caller will have no access to the provided time-related functions like time.After(), time.Before(), time.Equal() etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论