What does q{...} mean?

monarch_dodra monarchdodra at gmail.com
Mon Feb 24 10:40:13 PST 2014


On Monday, 24 February 2014 at 17:47:55 UTC, 1100110 wrote:
> On 2/24/14, 11:06, Gary Willoughby wrote:
>> On Monday, 24 February 2014 at 11:53:00 UTC, anonymous wrote:
>>> On Monday, 24 February 2014 at 11:47:02 UTC, Namespace wrote:
>>>> On Monday, 24 February 2014 at 11:41:41 UTC, Gary Willoughby 
>>>> wrote:
>>>>> I keep seeing this syntax used a bit and i'm stumped to 
>>>>> what it
>>>>> means. What is it?
>>>>>
>>>>> enum foo = q{
>>>>> // ???
>>>>> };
>>>>
>>>> http://dlang.org/lex.html#DelimitedString
>>>
>>> It's a token string though, not a delimited string. See the
>>> section "Token Strings" on that page.
>>
>> What are they used for? Simpler for creating code at compile 
>> time?
>
> It allows IDE syntax highlighting and code completion to work 
> with strings that are going to be mixed in.
>
> You don't have to use it, in fact there's no difference between 
> this and a normal string.
>
> It's just nicer.

Well... it's more than just "looking" nicer: there *are* some 
differences:

For starters, a token string has no "terminating" character: You 
won't have to chose between " or `: It'll simply end with the 
"last" }. This means that if your mixin-string contains some 
strings itself, which itself contains quotes, you should have no 
problems with it. EG:
auto code = q{
     foreach(i; 0 .. 10)
     {
         writefln(`"hello" %s`, i);
     }
};

Notice how there is nothing special denoting the last "}" as "end 
of string": It's *just* the end of string because it is the 
closing brace. The only times I've had "issues" is if you plan to 
use the "qstring" inside a format (*awesome* for generating 
code), and the generated code itself contains a formatted write, 
in which case, you'll need to escape the % =>

auto code = q{
     foreach(i; 0 .. %s)
     {
         writefln("hello: %%s", i);
     }
};
mixin(format(code, 10));

Also, a "qstring" can only contain valid D tokens ("token 
string"). If your mixin string does not adhere some the base D 
syntaxic rules, you'll get a compilation error. In particular, 
you'll need balanced bracing/parenthesising, and correctly formed 
tokens.


More information about the Digitalmars-d-learn mailing list