字符串插值/字符串模板如何工作?

4

@lf_araujo在这个问题中问道::

如何在Genie中对字典进行排序?
var dic = new dict of string, string
dic["z"] = "23"
dic["abc"] = "42"
dic["pi"] = "3.141"
for k in sorted_string_collection (dic.keys)
    print (@"$k: $(dic[k])")
“@”在print(@ ...)和lines_add(@ ...)中的作用是什么? 这适用于Genie和Vala,因此我认为将其作为独立问题更合适。
概念性问题是:
在Vala和Genie中,字符串插值是如何工作的?
1个回答

4

Vala和Genie中有两种字符串插值的选项:

  1. printf-style functions:

    var name = "Jens Mühlenhoff";
    var s = string.printf ("My name is %s, 2 + 2 is %d", name, 2 + 2);
    

    This works using varargs, you have to pass multiple arguments with the correct types to the varargs function (in this case string.printf).

  2. string templates:

    var name = "Jens Mühlenhoff";
    var s = @"My name is $name, 2 + 2 is $(2 + 2)";
    

    This works using "compiler magic".

    A template string starts with @" (rather then " which starts a normal string).

    Expressions in the template string start with $ and are enclosed with (). The brackets are unneccesary when the expression doesn't contain white space like $name in the above example.

    Expressions are evaluated before they are put into the string that results from the string template. For expressions that aren't of type string the compiler tries to call .to_string (), so you don't have to explicitly call it. In the $(2 + 2) example the expression 2 + 2 is evaluated to 4 and then 4.to_string () is called with will result in "4" which can then be put into the string template.

PS:我在这里使用的是Vala语法,只需删除;即可转换为Genie。


请注意,尽管Genie官方没有在行末使用分号(;),编译器也不会报错。 - lf_araujo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接