dowdw44426 2015-03-20 18:44
浏览 15
已采纳

为什么结构文字是“文字的”

In golang what are struct literals?

Why is the following a literal even though there is a variable? And aren't structs literally variable, even when not const? So how does it make sense.

MyType{Field: var)

It has a variable and yet it's a "literal"?

Also why is it only called a "struct literal" when you first initialize it?

  • 写回答

1条回答 默认 最新

  • dongtaigan1594 2015-03-20 19:04
    关注

    Programming languages use the word "Literal" when referring to syntactic ways to construct some data structure. It means it's not constructed by creating an empty one and adding or subtracting as you go.

    Compare:

    MyType{Field: myVariable}
    

    to

    var x = new(MyType)
    x.Field = myVariable
    

    The benefit is that your code's appearance reflects the data structure in some way. The downside is that you have to know the layout in advance and have the content initialized already, not possible, if for instance, you're constructing a map with unknown keys.

    Here are links to the literals in the Go language specification. Notice that they all are syntactic ways to define a data structure:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?