Skip to content

Inner constructor type constraint fails with UndefVarError in iteration #38888

@david-pl

Description

@david-pl

Consider the following bit of code:

struct MyStruct{T}
    x::T
    function MyStruct(x::S) where S<:Int
        new{S}(x)
    end
end
n = 3
# MyStruct(n) # works if you uncomment this line
[MyStruct(n) for i=1:3]

This will fail with an UndefVarError: S not defined. Once this error is thrown, it is not possible to construct MyStruct anymore. However, when restarting Julia constructing an instance of MyStruct in global scope works. If you then execute the list comprehension it also works.
Note that the same happens if you use a function instead of the list comprehension, inside of which MyStruct(n) is called, so I guess it's related to scoping.

A simple workaround is to relax the type constraint, e.g. S<:Integer works as expected. Still, it's strange that the list comprehension works when MyStruct is constructed in global scope before.

Version info:

Julia Version 1.5.3
Commit 788b2c77c1 (2020-11-09 13:37 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-9.0.1 (ORCJIT, skylake)

Metadata

Metadata

Assignees

Labels

bugIndicates an unexpected problem or unintended behavior

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions