zoukankan      html  css  js  c++  java
  • go语言的匿名函数

    没什么好说的, 见一个,熟悉一个:

    package main

    import (
    "fmt"
    )

    func main() {
    func() {
    fmt.Printf("func 1 ")
    }()

    func(x int) {
    fmt.Printf("func 2, x is %d ", x)
    }(2)

    a := func(x int) int {
    fmt.Printf("func 3, x is %d ", x)
    return 5
    }
    fmt.Println(a(3))

    fmt.Printf("%T ", func() {
    fmt.Printf("func 1 ")
    })

    fmt.Printf("%T ", func(x int) {
    fmt.Printf("func 2, x is %d ", x)
    })

    fmt.Printf("%T ", a)
    }
    结果:

    func 1
    func 2, x is 2
    func 3, x is 3
    5
    func()
    func(int)
    func(int) int

    继续看:

    package main

    import (
    "fmt"
    )

    func main() {
    test(func(x string) {
    fmt.Println(x)
    })
    }

    func test(f func(string)) {
    f("hello")
    }
    结果:hello

    但如下都错误, 想想为什么:

    package main

    import (
    "fmt"
    )

    func main() {
    func() {
    fmt.Printf("func 1 ")
    }
    }
    package main

    import (
    "fmt"
    )

    func main() {
    test(func g(x string) {
    fmt.Println(x)
    })
    }

    func test(f func(string)) {
    f("hello")
    }

    最后, 看看下面三个正确程序的:

    package main

    import (
    "fmt"
    )

    var x = "hello"

    func main() {
    test(func (x *string) {
    *x = "world"
    })

    fmt.Println(x)
    }

    func test(f func(*string)) {
    }
    package main

    import (
    "fmt"
    )

    func main() {
    var s1 = "hello"
    var s2 = "world"

    test(func(x *string, y *string) {
    *x += "_123"
    *y += "_456"
    }, &s1, &s2)

    fmt.Println(s1, s2) // hello_123 world_456
    }

    func test(f func(*string, *string), s1 *string, s2 *string) {
    f(s1, s2)
    }
    package main

    import (
    "fmt"
    )

    var s1 = "hello"
    var s2 = "world"

    func main() {
    test(func(x *string, y *string) {
    *x += "_123"
    *y += "_456"
    })

    fmt.Println(s1, s2) // hello_123 world_456
    }

    func test(f func(*string, *string)) {
    f(&s1, &s2)
    }
    不多说。

  • 相关阅读:
    对比Microsoft RemoteFX与VMware PCoIP
    SATA port selector and port muliplier 产品
    从并行 SCSI 到串行 SCSI
    转:快速远程桌面——Nomachine NX(ubuntu 10.10安装NX详解)
    全面分析:SATA2硬盘的发展和优缺点
    axel vpc
    转:网络带宽测量工具之iperf
    转:使用测试工具iPerf监控无线网络性能
    远程维护Helpdesk应用VNC
    QOS定义
  • 原文地址:https://www.cnblogs.com/cxy2020/p/15172200.html
Copyright © 2011-2022 走看看