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 關注
- 247 瀏覽
添加回答
舉報