go - 了解go复合文字

标签 go composite-literals

为什么分配给的函数值不是复合文字?

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:= ...行(应该是复合类型)很容易与第一行混淆。
  • 除了 body 之外,功能还有另外一件事- 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/

    相关文章:

    go - 如何使用 http.ServeContent() 处理修改时间?

    node.js - GCF 部署失败(地区/计费)

    json - 使用 golang 将 xml 转换为 swagger 2.0 规范

    go - for循环初始化器中的结构

    dictionary - 匿名结构,结构{}{}和{}的区别

    go - 防止在结构初始化中丢失字段

    go - 如何在 Goreleaser 中为每个目标设置 `-ldflags` 值?

    json - 使用数组转换JSON

    oop - 将其他pkg的类型嵌入到我的中,并通过字面量进行初始化

    pointers - 在 Golang 中赋值