理解go复合文字
为什么f的函数值赋值不是复合文字理解go复合文字,go,composite-literals,Go,Composite Literals,为什么f的函数值赋值不是复合文字 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())
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())
}
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())
}
主程序包
进口(
“fmt”
)
func main(){
var x int=0
var f func()int
f=func()int{x++;返回x*x}/您需要格式化它
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())
}
主程序包
进口(
“fmt”
)
func main(){
var x int=0
var f func()int
f=(func()int{x++;return x*x})//f=func()int{x++;return x*x}
看起来像复合文字吗?
(不太可能)
作为:
复合文字为结构、数组、切片和映射构造值……它们由文字类型和括号绑定的元素列表组成
为了让这句话更清楚,下面是复合文字的产生式规则:
CompositeLit = LiteralType LiteralValue .
您可以看到,的生成规则是:
而且,看起来完全不像这样。基本上,它是一个语句列表
:
FunctionBody = Block .
Block = "{" StatementList "}" .
StatementList = { Statement ";" } .
为什么函数不能构造为复合文字?
我无法找到任何书面答案,但最简单的假设是,主要原因如下:
- 避免混淆。下面是一个示例,如果允许它为函数构造复合文字:
s:=…
行(应该是复合类型)很容易与第1行混淆
- 除了body之外,函数还有一件更重要的事情--。如果可以为函数构造复合文字,如何定义它的参数和返回参数名称?可以在类型定义中定义名称--但这会导致不灵活(有时需要使用不同的参数名称)和如下代码:
看起来太不清楚了,因为不清楚它实际使用了什么x
变量。函数赋值看起来不像复合文字。复合文字是一个逗号分隔的键控元素列表,周围有花括号。函数语法也使用花括号,这一事实并不使它看起来像复合l“我找不到任何文件化的答案”你走吧:当你考虑争论和命名返回值时,你会遇到麻烦。
type SquareFunc func() int
type Square struct {
Function SquareFunc
}
func main() {
f := SquareFunc{ return 1 }
s := Square{ buildSquareFunc() }
}
type SquareFunc func(int x) int
func main() {
x := 1
f := SquareFunc{
x++
return x * x
}
f(2)
}