julia
julia copied to clipboard
Comma in struct definition leads to error & defined singleton struct
julia> struct Foo
value::Int,
name::Int
end
ERROR: UndefVarError: value not defined
Stacktrace:
[1] top-level scope
@ REPL[1]:1
julia> Foo
Foo
julia> Base.issingletontype(Foo)
true
julia> fieldtypes(Foo)
()
julia> fieldnames(Foo)
()
That ,
isn't valid there in any form, so shouldn't this throw a syntax error? Or any better error at all, instead of defining a singleton type?
Also probably related:
julia> struct Bar{T}
value::Union{Nothing, T},
name::T
end
ERROR: UndefVarError: T not defined
Stacktrace:
[1] top-level scope
@ REPL[2]:1
which leads to Bar
being a defined singleton as well.
Even worse, it doesn't always error:
julia> value = 1
1
julia> name = 2
2
julia> struct Foo
value::Int,
name::Int
end
I imagine that if a struct has a body other than field definitions, it is assumed to be a list of inner constructors and executed at the top-level, replacing the default inner constructor. In this case, the body is a tuple which is a valid top-level expression. Many syntax errors in a struct definition will result in a body which is not exclusively well-formed field declarations, so many syntax errors will trigger evaluation at top-level, a behavior users likely don't expect.
I'd like to fix this by making anything but a field declaration or a function declaration an error in a type definition, but it may break the following cases:
struct Unconstructable 1+1 end # This struct cannot be instantiated
struct DivisableByThree
value::Int
false || (three = 1 + 1 + 1)
function DivisableByThree(x)
iszero(x % three) || throw(ArgumentError("Not divisable by three"))
new(x)
end
end
wow. oops.
Why close?
because I closed the wrong one as a duplicate.
just ran into this
but it may break the following cases:
is that supposed to be allowed? 😳