我想定义一个结构:
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 中定义常量?
鉴于我同意上面关于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)