V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
billzhuang
V2EX  ›  Go 编程语言

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

  •  
  •   billzhuang ·
    billzhuang · 2022-12-20 20:21:51 +08:00 · 1926 次点击
    这是一个创建于 464 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    谢谢。

    7 条回复    2022-12-20 21:56:55 +08:00
    yaott2020
        1
    yaott2020  
       2022-12-20 20:57:25 +08:00 via Android
    incorrect 你已经把 time.Now()执行了,结果都出来了,后面那个 UTC 函数只是转换而已。因此结果就是固定的
    billzhuang
        2
    billzhuang  
    OP
       2022-12-20 21:02:40 +08:00
    @yaott2020 对。那我该怎么让 go 延迟执行这个 time.Now()呢?
    koebehshian
        4
    koebehshian  
       2022-12-20 21:36:06 +08:00   ❤️ 1
    函数返回函数
    ```
    // 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
        5
    SorcererXW  
       2022-12-20 21:40:28 +08:00   ❤️ 1
    abc : = time.Time.UTC

    fmt.Println(abd(time.Now()))
    GeruzoniAnsasu
        6
    GeruzoniAnsasu  
       2022-12-20 21:41:45 +08:00   ❤️ 1
    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
        7
    billzhuang  
    OP
       2022-12-20 21:56:55 +08:00 via iPhone
    谢谢各位,我懂了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3125 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:54 · PVG 20:54 · LAX 05:54 · JFK 08:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.