2 回答

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊
f = func() int{ x++; return x * x }看起來(lái)像復(fù)合文字嗎?
并不真地)
正如規(guī)范所述:
復(fù)合字面量為結(jié)構(gòu)、數(shù)組、切片和映射構(gòu)造值......它們由字面量的類型和后跟大括號(hào)綁定的元素列表組成。
為了使這個(gè)陳述更清楚,這里是復(fù)合文字的產(chǎn)生規(guī)則:
CompositeLit = LiteralType LiteralValue .
你可以看到,生產(chǎn)規(guī)則LiteralValue是:
LiteralValue = "{" [ ElementList [ "," ] ] "}" .
并且FunctionBody,看起來(lái)根本不像這樣?;旧希荢tatement's 的列表:
FunctionBody = Block .
Block = "{" StatementList "}" .
StatementList = { Statement ";" } .
為什么函數(shù)不能構(gòu)造為復(fù)合文字?
我無(wú)法找到任何記錄在案的答案,但最簡(jiǎn)單的假設(shè)是主要原因是:
避免混淆。這是示例,如果允許為函數(shù)構(gòu)造復(fù)合文字:
type SquareFunc func() int
type Square struct {
Function SquareFunc
}
func main() {
f := SquareFunc{ return 1 }
s := Square{ buildSquareFunc() }
}
s:= ...行(應(yīng)該是復(fù)合類型)很容易與第一行混淆。
除了身體,功能還有一個(gè)更重要的東西—— Signature。如果您可以為函數(shù)構(gòu)造復(fù)合文字,您將如何定義它的參數(shù)并返回參數(shù)名稱?您可以在類型定義中定義名稱——但這會(huì)導(dǎo)致不靈活(有時(shí)您想使用不同的參數(shù)名稱)和代碼如下:
type SquareFunc func(int x) int
func main() {
x := 1
f := SquareFunc{
x++
return x * x
}
f(2)
}
看起來(lái)太不清楚了,因?yàn)閤它實(shí)際使用的變量并不明顯。

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
你需要格式化它。
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在開(kāi)始您的功能代碼之前編寫(xiě)
- 2 回答
- 0 關(guān)注
- 243 瀏覽
添加回答
舉報(bào)