Julia: `invalid redefinition of constant` after an invalid struct definition

Created on 3 Jun 2019  路  3Comments  路  Source: JuliaLang/julia

Summary

I used incorrect syntax to define a struct at the REPL. After this, attempting to redefine the struct with correct syntax fails with invalid redefinition of constant. I would expect that, since the initial struct definition was invalid, it would not be defined at all.

Current behavior

julia> struct MyType
          m: Int
          n: Int
          end
ERROR: UndefVarError: m not defined
Stacktrace:
 [1] top-level scope at REPL[1]:1

julia> struct MyType
          m::Int
          n::Int
       end
ERROR: invalid redefinition of constant MyType
Stacktrace:
 [1] top-level scope at REPL[2]:1

Expected behavior

julia> struct MyType
          m: Int
          n: Int
          end
ERROR: UndefVarError: m not defined
Stacktrace:
 [1] top-level scope at REPL[1]:1

julia> struct MyType
          m::Int
          n::Int
       end

julia >
error handling

Most helpful comment

Ok, makes sense. This one off those cases where it's slightly annoying to have to restart a REPL session because of a typo. But I suppose that's true with any type definition.

(Actually, Revise.jl should be able to handle this, right? Will test later.)

All 3 comments

This is due to the fact that struct definitions can contain arbitrary expressions after the field names. For example

struct MyType
    f() = ...
end

is equivalent to

struct MyType
end
f() = ...

except that the definition of f is inside the struct definition's local scope. That's why we don't see this as an invalid struct definition.
But, I can't imagine there are any use cases for writing a range inside a struct, so we could probably add a better error for this case.

Ok, makes sense. This one off those cases where it's slightly annoying to have to restart a REPL session because of a typo. But I suppose that's true with any type definition.

(Actually, Revise.jl should be able to handle this, right? Will test later.)

This is probably worth special-casing since x: Int instead of x::Int is such an easy mistake to make, and couldn't reasonably mean anything else.

Was this page helpful?
0 / 5 - 0 ratings