Skip to content

Golang iota 语法小坑点 #35

@RedCrazyGhost

Description

@RedCrazyGhost

起因

在自测时发现枚举状态值流转异常

代码做了类似下方伪代码的改动

type Enum int

const (
+    EnumDebug = -1
     EnumNone = iota
     EnumWarn
     EnumInfo
-    EnumDebug = -1
)

尝试

分别测试了如下枚举常量顺序的打印结果

type Enum int

const (
    EnumDebug = -1   // -1
    EnumNone = iota  // 1
    EnumWarn         // 2
    EnumInfo         // 3
)
type Enum int

const (
    EnumNone = iota    // 0
    EnumWarn           // 1
    EnumInfo           // 2
    EnumDebug = -1     // -1
)
type Enum int

const (
    EnumDebug = -1     // -1
    EnumNone           // -1
    EnumWarn = iota    // 2
    EnumInfo           // 3
)

golang 在对于 iota 关键字的处理上和我想象的存在一些出入

在官方文档中对 ConstSpec 解释中可见一斑

Within a parenthesized const declaration list the expression list may be omitted from any but the first ConstSpec. Such an empty list is equivalent to the textual substitution of the first preceding non-empty expression list and its type if any. Omitting the list of expressions is therefore equivalent to repeating the previous list. The number of identifiers must be equal to the number of expressions in the previous list.
在用小括号括起来的const声明列表中,表达式列表可以从除第一个 ConstSpec 之外的任何一个 ConstSpec 中省略。这样的空列表等价于前面第一个非空表达式列表及其类型的文本替换(如果有的话)。因此,省略表达式列表等同于重复前面的列表。标识符的数量必须等于前一个列表中的表达式的数量。

总结

在常量小括号中使用 iota 的值从0开始,随每一行声明递增并且进行表达式计算,对于不符合 iota 计算表达式的赋值,都要放到最后处理

参考文档

Go ConstSpec
Go Wiki: Iota

Metadata

Metadata

Assignees

No one assigned

    Labels

    Golangfa-brands fa-golang

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions