How does string interpolation / string templates work?

…衆ロ難τιáo~ 提交于 2019-12-11 04:15:40

问题


@lf_araujo asked in this question:

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])")

What is the function of @ in print(@ ... ) and lines_add(@ ...)?

As this is applicable to both Genie and Vala, I thought it would be better suited as a stand-alone question.

The conceptual question is:

How does string interpolation work in Vala and Genie?


回答1:


There are two options for string interpolation in Vala and 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: I'm using Vala syntax here, just remove the ;s to convert to Genie.



来源:https://stackoverflow.com/questions/39437587/how-does-string-interpolation-string-templates-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!