为什么分配给和的函数值不是复合文字?
Go lang规范Composite literals如下所述,因此无法使用Composite Literal构造函数值。
Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated
但是,在代码中分配给 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())
}
最佳答案
f = func() int{ x++; return x * x }
是否看起来像复合文字?
并不真地)
作为spec states:
Composite literals construct values for structs, arrays, slices, and maps... They consist of the type of the literal followed by a brace-bound list of elements.
为了使该语句更清楚,这是复合文字的生产规则:
CompositeLit = LiteralType LiteralValue .
您可以看到
LiteralValue
的生产规则是:LiteralValue = "{" [ ElementList [ "," ] ] "}" .
和
FunctionBody
,看起来根本不是这样。基本上,它是Statement
的列表: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
变量并不明显。
关于go - 了解go复合文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61440004/