为什么对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())
}
牛魔王的故事
拉丁的传说
相关分类