This seems to work:
@eval struct $sym
value::String
function $sym(v::String)
$(
if len === nothing
nothing
else
:(length(v) == $len || throw(DomainError(v, "")))
end
)
new(v)
end
julia> sym2("aa")
sym2("aa")
julia> sym2("aaaa")
ERROR: DomainError with aaaa:
Stacktrace:
[1] sym2(v::String)
@ Main ./REPL[422]:8
[2] top-level scope
@ REPL[431]:1
julia> sym1("aaaa")
sym1("aaaa")
Are you sure this is the best way to handle your use case though? Obviously you are the best judge of that, and perhaps your real use is more complex, but for something like this I’d probably use a parametric type instead of defining types in a for loop
edit: looks like you can also simplify to
@eval struct $sym
value::String
function $sym(v::String)
if $len !== nothing
length(v) == $len || throw(DomainError(v, ""))
end
new(v)
end