无法制作函数参数

问题描述 投票:0回答:1

为什么我不能执行以下操作:

package main

import (
    "fmt"
)

func main() {
    run(hello("Hello"))
}

func hello(str string) {
    fmt.Println(str)
}

func run(f func(str string)) {
    f(str)
}

我可以做到这一点,但我想要参数。

package main

import (
    "fmt"
)

func main() {
    run(hello)
}

func hello() {
    fmt.Println("Hello")
}

func run(f func()) {
    f()
}
go
1个回答
0
投票

run(...)
函数的函数签名是错误的。但是我明白了,这是更正后的版本:

package main

import (
    "fmt"
)

func main() {
    run(hello)
}

func hello(str string) {
    fmt.Println(str)
}

func run(f func(str string)) {
    f("Hello")
}

您必须在调用函数的签名中命名要调用的函数的参数

© www.soinside.com 2019 - 2024. All rights reserved.