使用Haxe 3 ,通过字符串插值,不再需要手动连接字符串的各部分。一个特定的标识符,通过美元符号 $ 在一个单引号括起来的字符串中,像连接标识符一样被执行:
With Haxe 3 it is no longer necessary to manually concatenate parts of a string due to the introduction of String Interpolation. Special identifiers, denoted by the dollar sign $ within a String enclosed by single-quote ’ characters, are evaluated as if they were concatenated identifiers:
var x = 12;
// The value of x is 12
trace(’The value of x is $x’);
此外,可以包括完整的表达式到字符串中,通过使用 ${expr} ,expr 是任何有效的Haxe 表达式:
Furthermore, it is possible to include whole expressions in the string by using ${expr}, with expr being any valid Haxe expression:
var x = 12;
// The sum of 12 and 3 is 15
trace(’The sum of $x and 3 is ${x + 3}’);
字符串插值是一个编译时功能,不会对运行时性能产生影响。上面的例子和手动连接是等效的,和手动连接编译器生成相同的内容:
String interpolation is a compile-time feature and has no impact on the runtime. The above example is equivalent to manual concatenation, which is exactly what the compiler generates:
trace("The sum of " + x +
" and 3 is " + (x + 3));
当然,使用单引号括起来的字符串即使没有任何插值仍然是有效的,但是注意美元符号因为它会触发插值。如果一个实际的美元符号被使用,可以使用 $$ 双美元符号代替。
Of course the use of single-quote enclosed strings without any interpolation remains valid, but care has to be taken regarding the $ character as it triggers interpolation. If an actual dollar-sign should be used in the string, $$ can be used.
Haxe3之前的字符串插值
花絮: Haxe3之前的字符串插值 从Haxe 2.09之后字符串插值就作为一个Haxe功能被引入。在那之前,必须使用宏 Std.format,跟新的字符串插值语法相比,即慢而且不够灵活。 [warning] Trivia: String Interpolation before Haxe 3 String Interpolation has been a Haxe feature since version 2.09. Back then, the macro Std.format had to be used, being both slower and less comfortable than the new string interpolation syntax.