簡體   English   中英

如何在Julia-lang中初始化復合類型並在不將其作為函數參數傳遞的情況下使所有函數均可訪問?

[英]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的用法,但不確定是否會改變任何內容)

  1. 在Julia中,您可以定義全局變量。 每個Julia模塊(或裸模塊)都有其全局范圍。 如果聲明全局變量const則其類型可能不會更改(但綁定到值可能會更改)。
  2. 問題的第二部分是這種全局常數的可變性。 如果全局常量變量的類型是不可變的(例如數字,字符串, 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手冊》的相關部分:

編輯:在g函數的定義中添加了缺少的global關鍵字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM