
https://go.dev/play/p/xgmb2tPtMfw
package main import ( "fmt" "time" ) func main() { // incorrect abc := time.Now().UTC fmt.Println(abc()) time.Sleep(1000000000) fmt.Println(abc()) fmt.Println("-------------------------------") // correct bcd := time.Now fmt.Println(bcd()) time.Sleep(1000000000) fmt.Println(bcd()) } 上面那种写法,返回的是固定值,编译器优化?
如果我不想自定义一个函数,类似
func utc() time.Time { return time.Now().UTC() } abc := utc ... 或者匿名函数,类似
abc := func() time.Time { return time.Now().UTC()} 我就想直接 inline 定义这个匿名函数,咋整?
谢谢。
1 yaott2020 2022 年 12 月 20 日 via Android incorrect 你已经把 time.Now()执行了,结果都出来了,后面那个 UTC 函数只是转换而已。因此结果就是固定的 |
2 billzhuang OP @yaott2020 对。那我该怎么让 go 延迟执行这个 time.Now()呢? |
3 Yourshell 2022 年 12 月 20 日 via Android |
4 koebehshian 2022 年 12 月 20 日 函数返回函数 ``` // You can edit this code! // Click here and start typing. package main import ( "fmt" "time" ) func returnTimeFunc() func() time.Time { return time.Now } func main() { // correct bcd := returnTimeFunc() fmt.Println(bcd()) } ``` |
5 SorcererXW 2022 年 12 月 20 日 abc : = time.Time.UTC fmt.Println(abd(time.Now())) |
6 GeruzoniAnsasu 2022 年 12 月 20 日 golang 中的 func 是一等公民( first-class ) bcd := func() func() time.Time { return time.Now } bcd_ := bcd() fmt.Println(bcd_()) fmt.Println(func() time.Time { return time.Now() }()) 都是可以的 |
7 billzhuang OP 谢谢各位,我懂了。 |