String macro with trailing argument

I am trying to get the string literal macro example with a trailing argument from the manual to work (end of section linked), with the MWE

struct Foo
    str::String
    flag::Bool
end

macro foo_str(str, flag)
    _flag = if flag == "true"
        true
    elseif flag == "false"
        false
    else
        error("need a boolean flag, got $(flag)")
    end
    Foo(str, _flag)
end

foo"bar"true

which gives me the error

julia> foo"bar"true
ERROR: LoadError: MethodError: no method matching var"@foo_str"(::LineNumberNode, ::Module, ::String)
The function `@foo_str` exists, but no method is defined for this combination of argument types.

Closest candidates are:
  var"@foo_str"(::LineNumberNode, ::Module, ::Any, ::Any)
   @ Main REPL[10]:1

What am I missing?

The problem is that, since true is numeric literal, this is parsed as a multiplication:

julia> :(foo"bar"true)
:(foo"bar" * true)

Just use t and f as your flags and it should work … normally these string-macro flags are one-character, like in regexes.

3 Likes