为了账号安全,请及时绑定邮箱和手机立即绑定

理解 go 复合字面量

理解 go 复合字面量

Go
阿晨1998 2022-06-01 12:25:51
为什么对f的函数赋值不是复合文字?Go lang 规范复合文字如下所述,因此不能用复合文字构造函数值。复合文字为结构、数组、切片和映射构造值,并在每次评估它们时创建一个新值但是,代码中对f的函数赋值看起来像是func() int类型的复合文字表达式。函数对象不能构造为复合文字是否有原因?package mainimport (    "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())}
查看完整描述

2 回答

?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

f = func() int{ x++; return x * x }看起来像复合文字吗?

并不真地)


正如规范所述:


复合字面量为结构、数组、切片和映射构造值......它们由字面量的类型和后跟大括号绑定的元素列表组成。


为了使这个陈述更清楚,这里是复合文字的产生规则:


CompositeLit  = LiteralType LiteralValue .

你可以看到,生产规则LiteralValue是:


LiteralValue  = "{" [ ElementList [ "," ] ] "}" .

并且FunctionBody,看起来根本不像这样。基本上,它是Statement's 的列表:


FunctionBody = Block .

Block = "{" StatementList "}" .

StatementList = { Statement ";" } .

为什么函数不能构造为复合文字?

我无法找到任何记录在案的答案,但最简单的假设是主要原因是:


避免混淆。这是示例,如果允许为函数构造复合文字:

type SquareFunc func() int


type Square struct {

    Function SquareFunc

}


func main() {

    f := SquareFunc{ return 1 }

    s := Square{ buildSquareFunc() }

}

s:= ...行(应该是复合类型)很容易与第一行混淆。


除了身体,功能还有一个更重要的东西—— Signature。如果您可以为函数构造复合文字,您将如何定义它的参数并返回参数名称?您可以在类型定义中定义名称——但这会导致不灵活(有时您想使用不同的参数名称)和代码如下:

type SquareFunc func(int x) int


func main() {

    x := 1


    f := SquareFunc{ 

        x++

        return x * x

    }

    f(2)

}

看起来太不清楚了,因为x它实际使用的变量并不明显。


查看完整回答
反对 回复 2022-06-01
?
拉丁的传说

TA贡献1789条经验 获得超8个赞

你需要格式化它。


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(func()int{ x++; return x * x})   // <--- Error with Invalid composite literal type: SQUARE 


   fmt.Println(g())

}

f使用.包装你的变量()。在 的情况下SQUARE,您需要func() int在开始您的功能代码之前编写


查看完整回答
反对 回复 2022-06-01
  • 2 回答
  • 0 关注
  • 276 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号