朱莉娅中有#define等效项吗?

M.E*_*.E. 3 julia

我正在实现一些基本状态机,其中一些状态在Julia中。

在CI中,将使用类似于以下内容的方式跟踪当前状态:

#define STOP 1
#define START 2
#define ERROR 3
Run Code Online (Sandbox Code Playgroud)

然后在比较等中使用友好常量。

if(state == STOP) {
    printf("Stop state.\n");
}
Run Code Online (Sandbox Code Playgroud)

在Julia中是否有与#define等效的东西?

Cam*_*nek 7

您可以使用一个枚举。枚举是使用@enum宏定义的:

@enum State STOP START ERROR
Run Code Online (Sandbox Code Playgroud)

这将创建三个常量,STOPSTART,和ERROR所有类型的State。这意味着您可以按枚举类型调度函数:

import Base.println
function println(s::State)
    if s == STOP
        println("Stop state.")
    elseif s == START
        println("Start state.")
    else
        println("Error state.")
    end
end
Run Code Online (Sandbox Code Playgroud)
julia> s = STOP

julia> println(s)
Stop state.
Run Code Online (Sandbox Code Playgroud)

枚举可以转换为整数值:

julia> Int.([STOP, START, ERROR])
3-element Array{Int64,1}:
 0
 1
 2
Run Code Online (Sandbox Code Playgroud)

如您所见,枚举状态序列的默认整数值始于0。但是,您可以选择在使用@enum宏时为枚举显式设置整数值:

julia> @enum Heat LOW=1 MEDIUM=2 HIGH=3

julia> Int.([LOW, MEDIUM, HIGH])
3-element Array{Int64,1}:
 1
 2
 3
Run Code Online (Sandbox Code Playgroud)

需要注意的是在创造一个开关一样,当println上面的定义,你可以确信STOPSTARTERROR是唯一可能的值State对象。可以通过显式构造State对象来证明这一点:

julia> State(0), State(1), State(2)
(STOP::State = 0, START::State = 1, ERROR::State = 2)

julia> State(3)
ERROR: ArgumentError: invalid value for Enum State: 3
Stacktrace:
 [1] enum_argument_error(::Symbol, ::Int64) at ./Enums.jl:34
 [2] State(::Int64) at ./Enums.jl:139
 [3] top-level scope at none:0
Run Code Online (Sandbox Code Playgroud)


Jef*_*off 5

如果您确实想要尽可能接近的东西,可以#define <Symbol> <Integer>使用const

const STOP  = 1
const START = 2
const ERROR = 3
Run Code Online (Sandbox Code Playgroud)

  • 由于这也很重要,我想对于特定的`state`变量来说,使用枚举更有意义(即使问题没有明确要求时)。 (2认同)