[英]How to initialize a composite type in Julia-lang and be accessible to all functions without it being passed as a function parameter?
在Julia Lang
,如何在運行時分配composite type
的參數值並使其可被文件中的所有函數訪問?
我正在尋找與Java中的'static'關鍵字相似的功能。 這是為了避免在每次調用函數時都發送復合類型,因為復合類型是從一次讀取文件開始初始化的,並且許多函數都依賴該復合類型。 並且此后未更改,但在編譯時不知道這些值。 (我記得Julia中struct的用法,但不確定是否會改變任何內容)
const
則其類型可能不會更改(但綁定到值可能會更改)。 struct
s,元組,命名元組),則將無法更改其值。 但是,仍然可以將變量重新綁定到新值(只要新值具有適當的類型,我們將收到一條警告:綁定已更改-請參見下面的示例)。 Julia Base中這種方法的一個很好的例子是Base.GLOBAL_RNG
變量(可變變量除外)-它在Julia中擁有默認隨機數生成器的狀態。
這是一個使用struct
的簡單示例:
module E
struct A # immutable
x::Int
end
const a = A(1) # global constant in module E
f() = println("a: $a")
function g()
global a = A(10) # rebinding of a global variable requires global keyword
end
function h()
a.x = 100
end
end # module
如果在REPL中執行此操作,則可以測試行為:
julia> E.a # we test the value of a global variable in module E
Main.E.A(1)
julia> E.f() # function f() from this module can access it
a: Main.E.A(1)
julia> E.h() # we cannot mutate fields of a
ERROR: type is immutable
Stacktrace:
[1] setproperty! at .\sysimg.jl:9 [inlined]
[2] h() at .\REPL[1]:16
[3] top-level scope
julia> E.g() # but we can change the binding, we get a warning
WARNING: redefining constant a
Main.E.A(10)
julia> E.a
Main.E.A(10)
julia> E.a = E.A(1000) # the binding cannot be changed outside the module
ERROR: cannot assign variables in other modules
Stacktrace:
[1] setproperty!(::Module, ::Symbol, ::Main.E.A) at .\sysimg.jl:15
[2] top-level scope
如果在REPL中定義了全局常量,則重新綁定其值還會發出警告(以下是在REPL范圍中定義了全局變量的更多示例):
julia> global const z = E.A(5)
Main.E.A(5)
julia> z.x = 10
ERROR: type A is immutable
Stacktrace:
[1] setproperty!(::Main.E.A, ::Symbol, ::Int64) at .\sysimg.jl:9
[2] top-level scope
julia> z = E.A(2)
WARNING: redefining constant z
Main.E.A(2)
julia> z = "test" # we cannot change a type of const variable
ERROR: invalid redefinition of constant z
以下是《 Julia手冊》的相關部分:
global
關鍵字: https : //docs.julialang.org/en/latest/base/base/#global 編輯:在g
函數的定義中添加了缺少的global
關鍵字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.