2011-06-19 131 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"); 
    } 
}