请教一个函数返回函数的语法

2022-12-20 20:21:51 +08:00
 billzhuang

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 定义这个匿名函数,咋整?

谢谢。

1969 次点击
所在节点    Go 编程语言
7 条回复
yaott2020
2022-12-20 20:57:25 +08:00
incorrect 你已经把 time.Now()执行了,结果都出来了,后面那个 UTC 函数只是转换而已。因此结果就是固定的
billzhuang
2022-12-20 21:02:40 +08:00
@yaott2020 对。那我该怎么让 go 延迟执行这个 time.Now()呢?
Yourshell
2022-12-20 21:23:11 +08:00
koebehshian
2022-12-20 21:36:06 +08:00
函数返回函数
```
// 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())

}
```
SorcererXW
2022-12-20 21:40:28 +08:00
abc : = time.Time.UTC

fmt.Println(abd(time.Now()))
GeruzoniAnsasu
2022-12-20 21:41:45 +08:00
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() }())

都是可以的
billzhuang
2022-12-20 21:56:55 +08:00
谢谢各位,我懂了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/903801

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX