删除Julia中的Struct

删除Julia中的Struct,julia,Julia,我创建了一个复合类型 mutable struct Person id::Int64 end 这很好,所以我想像这样扩展类型 mutable struct Person id::Int64 contacts::Array{Int64} end 但我被告知,这是对常量Person的无效重新定义 如何删除类型?除了重新启动REPL,还有其他方法吗?(请说是。)不,如果不重新启动Julia,这是不可能的。不幸的是,这是为数不多的Revise.jl(如果有办法做到这一点,它可

我创建了一个复合类型

mutable struct Person
    id::Int64
end
这很好,所以我想像这样扩展类型

mutable struct Person
    id::Int64
    contacts::Array{Int64}
end
但我被告知,这是对常量Person的无效重新定义


如何删除类型?除了重新启动REPL,还有其他方法吗?(请说是。)

不,如果不重新启动Julia,这是不可能的。

不幸的是,这是为数不多的
Revise.jl
(如果有办法做到这一点,它可能会在
Revise
中实现)。因此,即使使用
Revise
,您当前也必须重新启动julia以更改类型的定义

让我来解释一下为什么目前无法做到这一点:

julia> struct Person
           name :: String
       end

julia> alice = Person("Alice")
Person("Alice")

# Imagine you have some magic trick that makes this possible:
julia> struct Person
           id   :: Int
           name :: String
       end

julia> bob = Person(42, "Bob")
Person(42, "Bob")

# What should be the type of alice now?
julia> alice
Person("Alice") # Not consistent with the current definition of Person



在一个新类型的开发阶段,我有时会使用以下技巧。不过,这有点像黑客,我不确定我是否应该建议这样做:使用风险自负

其思想在于对实际的类型定义进行编号,将类型命名为
Person1
Person2
,版本号在定义每次更改时递增。为了在方法定义中使这些编号类型名称的使用遍布您的代码,您可以临时将最新的定义别名为一个通用的未编号名称

例如,假设您有一个
Person
类型的第一个实现,只有一个名称:

# First version of the type
julia> struct Person1
           name :: String
       end

# Aliased to just "Person"
julia> Person = Person1
Person1

# Define methods and instances like usual, using the "Person" alias
julia> hello(p::Person) = println("Hello $(p.name)")
hello (generic function with 1 method)

julia> alice = Person("Alice")
Person1("Alice")

julia> hello(alice)
Hello Alice
现在,假设您要更改
Person
类型的定义以添加
id
字段:

# Second version of the type: increment the number
# This is strictly a new, different type
julia> struct Person2
           id   :: Int
           name :: String
       end

# But you can alias "Person" to this new type
julia> Person = Person2
Person2

# It looks as though you update the definition of the same "hello" method...
julia> hello(p::Person) = println("Hello $(p.name), you have id: $(p.id)")
hello (generic function with 2 methods)

# ...when in reality you are defining a new method
julia> methods(hello)
# 2 methods for generic function "hello":
[1] hello(p::Person2) in Main at REPL[8]:1
[2] hello(p::Person1) in Main at REPL[3]:1

julia> bob = Person(42, "Bob")
Person2(42, "Bob")

julia> hello(bob)
Hello Bob, you have id: 42

# alice is still of type "Person1", and old methods still work
julia> hello(alice)
Hello Alice

您是否尝试过使用
Revise
?Revise不处理结构的重新定义,请参阅。对不起,这句话应该说明什么?我猜“如果不重新启动Julia,这是不可能的。”我非常喜欢您的回答。它回答了问题,解释了背景,并提供了一个非常好的解决方法。谢谢。