如何在Julia struct中定义常量

问题描述 投票:0回答:2

我想定义一个结构:

struct unit_SI_gen
    x::Float32
    const c = 2.99792458e8
    speed(x)=c*x
end

但是,它会引发错误:

syntax: "c = 2.99792e+08" inside type definition is reserved

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

如何在struct中定义常量?

julia
2个回答
4
投票

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

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

3
投票

我第二个@Tasos的评论,你应该首先熟悉朱莉娅的结构。文档的相关部分可能是here

由于您将结构声明为struct(与mutable struct相反),因此它是不可变的,因此结构的所有(不可变)字段都是常量,因为它们无法更改。

julia> struct A
       x::Int
       end

julia> a = A(3)
A(3)

julia> a.x = 4
ERROR: type A is immutable
Stacktrace:
 [1] setproperty!(::A, ::Symbol, ::Int64) at .\sysimg.jl:19
 [2] top-level scope at none:0

请注意,它们在构造过程中获得了不可更改的值,而不是在结构定义中。

此外,方法通常应该位于结构定义之外。

© www.soinside.com 2019 - 2024. All rights reserved.