理解 go 复合字面量

为什么对f的函数赋值不是复合文字?


Go lang 规范复合文字如下所述,因此不能用复合文字构造函数值。


复合文字为结构、数组、切片和映射构造值,并在每次评估它们时创建一个新值


但是,代码中对f的函数赋值看起来像是func() int类型的复合文字表达式。


函数对象不能构造为复合文字是否有原因?


package main

import (

    "fmt"

)


func main(){

    var x int = 0


    var f func() int

    f = func() int{ x++; return x * x }  // <---- Why this cannot be a composite literal?


    fmt.Println(f())   // 1

    fmt.Println(f())   // 4

    fmt.Println(f())   // 9


    // Define a type for "func() int" type 

    type SQUARE func() int

    g := SQUARE{ x++; return x * x}   // <--- Error with Invalid composite literal type: SQUARE 


    fmt.Println(g())

}


阿晨1998
浏览 278回答 2
2回答

牛魔王的故事

f = func() int{ x++; return x * x }看起来像复合文字吗?并不真地)正如规范所述:复合字面量为结构、数组、切片和映射构造值......它们由字面量的类型和后跟大括号绑定的元素列表组成。为了使这个陈述更清楚,这里是复合文字的产生规则:CompositeLit&nbsp; = LiteralType LiteralValue .你可以看到,生产规则LiteralValue是:LiteralValue&nbsp; = "{" [ ElementList [ "," ] ] "}" .并且FunctionBody,看起来根本不像这样。基本上,它是Statement's 的列表:FunctionBody = Block .Block = "{" StatementList "}" .StatementList = { Statement ";" } .为什么函数不能构造为复合文字?我无法找到任何记录在案的答案,但最简单的假设是主要原因是:避免混淆。这是示例,如果允许为函数构造复合文字:type SquareFunc func() inttype Square struct {&nbsp; &nbsp; Function SquareFunc}func main() {&nbsp; &nbsp; f := SquareFunc{ return 1 }&nbsp; &nbsp; s := Square{ buildSquareFunc() }}s:= ...行(应该是复合类型)很容易与第一行混淆。除了身体,功能还有一个更重要的东西—— Signature。如果您可以为函数构造复合文字,您将如何定义它的参数并返回参数名称?您可以在类型定义中定义名称——但这会导致不灵活(有时您想使用不同的参数名称)和代码如下:type SquareFunc func(int x) intfunc main() {&nbsp; &nbsp; x := 1&nbsp; &nbsp; f := SquareFunc{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; x++&nbsp; &nbsp; &nbsp; &nbsp; return x * x&nbsp; &nbsp; }&nbsp; &nbsp; f(2)}看起来太不清楚了,因为x它实际使用的变量并不明显。

拉丁的传说

你需要格式化它。package mainimport (&nbsp; "fmt")func main(){&nbsp; &nbsp;var x int = 0&nbsp; &nbsp;var f func() int&nbsp; &nbsp;f = (func() int{ x++; return x * x })&nbsp; // <---- Why this cannot be a composite literal?&nbsp; &nbsp;fmt.Println(f())&nbsp; &nbsp;// 1&nbsp; &nbsp;fmt.Println(f())&nbsp; &nbsp;// 4&nbsp; &nbsp;fmt.Println(f())&nbsp; &nbsp;// 9&nbsp; &nbsp;// Define a type for "func() int" type&nbsp;&nbsp; &nbsp;type SQUARE func() int&nbsp; &nbsp;g := SQUARE(func()int{ x++; return x * x})&nbsp; &nbsp;// <--- Error with Invalid composite literal type: SQUARE&nbsp;&nbsp; &nbsp;fmt.Println(g())}f使用.包装你的变量()。在 的情况下SQUARE,您需要func() int在开始您的功能代码之前编写
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go