doutao8774 2018-11-16 04:51
浏览 50
已采纳

结构声明中的文字值

Say we have a struct like so:

type Foo struct {
  one string
  two int
}

is it possible to declare literal values for this, something like:

type Foo struct {
  one "foobar"
  two int
}

or

type Foo struct {
  one string
  two 5678
}

basically for some objects we might have a hardcoded value for a field.

  • 写回答

2条回答 默认 最新

  • dongpeng0127 2018-11-16 06:22
    关注

    No, Go does not support literal types (a la TypeScript). Moreover, it actually can't, because of zero values.

    Every type has a zero value which always exists and is always assignable to it. When variables of a type are declared, they are implicitly assigned to their type's zero value.

    • For integer (int, uint, int32, uint32, int64, uin64) or float (float32, float64) or complex (complex64 or complex128) types, this is just 0 (0.0 respectively).

    • For string types, this is the empty string "".

    • For slices, maps, pointers, channels, and interfaces, the zero value is nil.

    • For arrays (not slices: arrays are value-types with statically-known length); their zero value is just the zero value of the element type repeated to fill every slot

    • The zero value of a struct type is a struct all of whose fields are zero values

    In any case, because it is always possible for any type to have a zero value, it would be incompatible to create a type which only allows for any particular non-zero value.

    The best a literal type "foo" could possibly represent is that the value is either "foo" or the zero value "" (and no, Go doesn't support this anyway).

    The closest you'll be able to do is a constant declaration, or a receiver function that just-so-happens to return a fixed value instead of an actual field.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算