Go 我不知道';我不理解代码:result=quote123(func(x int)字符串{return fmt.Sprintf(";%b";,x)})

Go 我不知道';我不理解代码:result=quote123(func(x int)字符串{return fmt.Sprintf(";%b";,x)}),go,Go,我正在学习golang,对于一个将函数作为参数传递给另一个函数的代码,我不知道我列出的代码的含义 对于quote123函数,它将函数作为参数,如何将部分:func(x int)字符串{return fmt.Sprintf(“%b”,x)}传递到quote123函数中,即使是这样,如果该部分返回字符串,该字符串也不应该是函数quote123的参数 // convert types take an int and return a string value. type convert func(in

我正在学习golang,对于一个将函数作为参数传递给另一个函数的代码,我不知道我列出的代码的含义

对于quote123函数,它将函数作为参数,如何将部分:func(x int)字符串{return fmt.Sprintf(“%b”,x)}传递到quote123函数中,即使是这样,如果该部分返回字符串,该字符串也不应该是函数quote123的参数

// convert types take an int and return a string value.
type convert func(int) string

// value implements convert, returning x as string.
func value(x int) string {
    return fmt.Sprintf("%v", x)
}

// quote123 passes 123 to convert func and returns quoted string.
func quote123(fn convert) string {
    return fmt.Sprintf("%q", fn(123))
}

func main() {
    var result string

    result = value(123)
    fmt.Println(result)
    // Output: 123

    result = quote123(value)
    fmt.Println(result)
    // Output: "123"

    result = quote123(func(x int) string { return fmt.Sprintf("%b", x) })
    fmt.Println(result)
    // Output: "1111011"

    foo := func(x int) string { return "foo" }
    result = quote123(foo)
    fmt.Println(result)
    // Output: "foo"

    _ = convert(foo) // confirm foo satisfies convert at runtime
    // fails due to argument type
    // _ = convert(func(x float64) string { return "" })
}

quote123
接受接受整数参数并返回字符串的任何函数。在这段代码中传递给它的参数是一个函数文本,也称为一个附件或一个匿名函数,带有此签名。函数文字有两部分:

func(x int)字符串

这是函数文本的签名。这表明它与
quote123
采用的参数类型相匹配,即类型
convert
,一种定义为
type convert func(int)string

{返回fmt.Sprintf(“%b”,x)}

这是函数文本的主体或实现。这是调用函数文本时实际运行的代码。在本例中,它将整数
x
,将其格式化为二进制(这就是
%b
格式化谓词所做的)字符串,并返回该字符串

quote123
将此函数作为参数,使用整数(在本例中为整数
123
)调用它,然后获取它返回的字符串,并使用
%q
格式化谓词对其进行格式化,该动词围绕引号中给定的字符串

这样做的最终效果是123被传入,格式化为二进制(
1111011
),返回为字符串(
1111011
),然后用周围的引号再次格式化(
“1111011”
),最后打印到控制台

接受这样的函数文本允许您自定义调用函数时的行为
quote123
将始终返回带引号的字符串,但其中的内容可能会更改。例如,如果我改为使用以下文字:

func(x int)字符串{返回fmt.Sprintf(“%06d”,x)}

我会取回字符串
“000123”
,因为格式化动词
%06d
表示将其打印为一个整数,宽度为6,并用0代替空格字符填充。如果我改为使用:

func(x int)字符串{返回“hello world”}


无论调用哪个整数,我都会返回字符串“hello world”。

从围棋开始。现在做练习。重复一遍。然后回到那个问题。你是在问a是什么吗?我想知道quote123如何接受func(x int)字符串{return fmt.Sprintf(“%b”,x)}作为它的参数,以及它如何生成最终结果1111011@crazyA:它是一个函数文本,与
convert
的签名匹配。它会生成
1111011
,因为它返回的是。我不知道如何在这方面展开。您能更具体地说明您不了解的内容吗?func quote123(fn convert)string{….}这是否意味着quote123是一个函数,接受函数作为参数,并返回字符串作为,我如何知道参数需要是函数返回字符串的函数?类型
convert
是一个接受整数并返回字符串的函数
quote123
接受转换,因此它接受带有该签名的任何函数(
func(int)string
quote123
还返回一个字符串,这就是为什么
quote123
在其签名末尾也有
string
quote123
的签名是
func(convert)string
,但可以像
func(func(int)string)string
一样轻松编写。外部
()
中的所有内容都是参数列表,在本例中是作为参数的单个函数。整个
func(int)字符串
就是这个参数的类型。我想你指的是“”,而不是“enclosure”。但这不是一个闭包的例子,因为没有变量被关闭。