如何在 Julia 结构中定义常量

Mr.*_*.CG 0 julia

我想定义一个结构:

struct unit_SI_gen
    x::Float32
    const c = 2.99792458e8
    speed(x)=c*x
end
Run Code Online (Sandbox Code Playgroud)

但是,它引发了一个错误:

syntax: "c = 2.99792e+08" inside type definition is reserved
Run Code Online (Sandbox Code Playgroud)

我知道我不能在 python 中使用 struct 作为类,但我找不到如何解决这个问题。

如何在 struct 中定义常量?

Bog*_*ski 5

鉴于我同意上面关于struct在 Julia 中的正常使用所说的内容,实际上可以使用内部构造函数定义问题中请求的内容:

struct unit_SI_gen{F} # need a parametric type to make it fast
    x::Float32
    c::Float64 # it is a constant across all unit_SI_gen instances
    speed::F # it is a function

    function unit_SI_gen(x)
        c = 2.99792458e8
        si(x) = c*x
        new{typeof(si)}(x, c, si)
    end
end
Run Code Online (Sandbox Code Playgroud)

  • 不同之处在于(我相信你知道 :))`x` 可能会跨实例而变化,而 `c` 可能不会。至少这是我认为所要求的 - 在 Java 中寻找类似“final static”的东西。当然,这仅在 `c` 是位类型时才成立(但这是要求的)。如果 `c` 是可变的,那么它的指针在实例之间会有所不同,除非它是在编译时使用宏分配的(现在我们陷入了更加混乱的境地)。 (2认同)