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它实际使用的变量并不明显。

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在开始您的功能代码之前编写
- 2 回答
- 0 关注
- 276 浏览
添加回答
举报