2011-06-19 132 views
3

在 “The d程序设计语言” 的书,我看到以下内容:D2:switch语句和变量

Usually the case expressions are compile-time constants, but D allows variables, too, and guarantees lexical-order evaluation up to the first match.

代码:

void main() 
{ 
    string foo = "foo"; 
    string bar = "bar"; 

    string mrX; 

    switch (mrX) 
    { 
     case foo: 
     writeln(foo); 
     break; 
     case bar: 
     writeln(bar); 
     break; 
     default: 
     writeln("who knows"); 
    } 
} 

结果:

Error: case must be a string or an integral constant, not foo

有什么不对?

PS。我使用DMD32 D编译器v2.053

+0

foo和bar可能需要是不可变的... –

+1

TDPL说有很多事情说DMD还没有实现。幸运的是DMD正在快速改善,所以希望这不会太长时间:-) –

回答

2

也许这是一个错误,但它不能使用变量。我可以让你的例子像这样工作:

void main() 
{ 
    immutable string foo = "foo"; 
    const string bar = "bar"; 
    string mrX; 
    switch (mrX) 
    { 
     case to!string(foo): 
     writeln(foo); 
     break; 
     case to!string(bar): 
     writeln(bar); 
     break; 
     default: 
     writeln("who knows"); 
    } 
}