插入字串

插補字串是可讓您將 F# 運算式內嵌到其中的字串。 在字串的值可能根據值或運算式的結果而變更的多種情況下,插補字串都可派上用場。

語法

$"string-text {expr}"
$"string-text %format-specifier{expr}"
$"""string-text {"embedded string literal"}"""
$$"""string-text %%format-specifier{{expr}}"""

備註

插補字串可讓您在字串常值內的「空隙」內撰寫程式碼。 以下是基本範例:

let name = "Phillip"
let age = 30
printfn $"Name: {name}, Age: {age}"

printfn $"I think {3.0 + 0.14} is close to {System.Math.PI}!"

每個成對大括弧 {} 之間的內容,都可以是任何 F# 運算式。

若要逸出 {} 成對大括弧,請撰寫兩個大括弧,如下所示:

let str = $"A pair of braces: {{}}"
// "A pair of braces: {}"

具型別的插補字串

插補字串也可以使用 F# 格式規範來強制執行型別安全。

let name = "Phillip"
let age = 30

printfn $"Name: %s{name}, Age: %d{age}"

// Error: type mismatch
printfn $"Name: %s{age}, Age: %d{name}"

在上述範例中,程式碼在傳入值時將 agename 互相誤植了。 由於插補字串使用了格式規範,因此這是編譯錯誤,而不是微小的執行階段錯誤 (bug)。

逐字插補字串

F# 支援具有三引號的逐字插補字串,讓您能夠內嵌字串常值。

let age = 30

printfn $"""Name: {"Phillip"}, Age: %d{age}"""

格式規範

格式規範可以是 printf 樣式或 .NET 樣式。 printf 樣式規範是採用純文字格式的規範,放在大括弧之前。 例如:

let pi = $"%0.3f{System.Math.PI}"  // "3.142"
let code = $"0x%08x{43962}"  // "0x0000abba"

格式規範 %A 特別適合用來產生結構化 F# 資料的診斷輸出。

let data = [0..4]
let output = $"The data is %A{data}"  // "The data is [0; 1; 2; 3; 4]"

.NET 樣式規範是可與 String.Format 搭配使用的規範,放在大括弧內的 : 後面。 例如:

let pi = $"{System.Math.PI:N4}"  // "3.1416"
let now = $"{System.DateTime.UtcNow:``yyyyMMdd``}" // e.g. "20220210"

如果 .NET 樣式規範包含不常見的字元,可以使用雙反引號將其逸出:

let nowDashes = $"{System.DateTime.UtcNow:``yyyy-MM-dd``}" // e.g. "2022-02-10"

對齊插補字串中的運算式

您可以藉由使用 | 並指定空格數目,在插補字串內將運算式靠左對齊或靠右對齊。 下列插補字串會將左、右運算式分別向左、向右以七個空格對齊。

printfn $"""|{"Left",-7}|{"Right",7}|"""
// |Left   |  Right|

插補字串和 FormattableString 格式

您也可以套用符合 FormattableString 規則的格式:

let speedOfLight = 299792.458
printfn $"The speed of light is {speedOfLight:N3} km/s."
// "The speed of light is 299,792.458 km/s."

此外,插補字串也可以透過型別註釋將型別檢查為 FormattableString

let frmtStr = $"The speed of light is {speedOfLight:N3} km/s." : FormattableString
// Type: FormattableString
// The speed of light is 299,792.458 km/s.

請注意,型別註釋必須置於插補字串運算式本身。 F# 不會隱含地將插補字串轉換成 FormattableString

字串內插補點的延伸語法

從 F# 8 開始,當您使用已包含多個 {}% 字元的文字時,可以使用延伸字串內插補點語法來移除逸出的需求。

三引號字串常值可以從多個 $ 字元開始,這會變更開啟和關閉內插補點所需的大括弧數目。 在這些字串常值中,並不需要逸出 {} 字元:

let str = $$"""A string containing some {curly braces} and an {{"F#" + " " + "expression"}}."""
// "A string containing some {curly braces} and an F# expression."
let another = $$$"""A string with pairs of {{ and }} characters and {{{ "an F# expression" }}}."""
// "A string with pairs of {{ and }} characters and an F# expression."""

格式規範所需的 % 字元數會以相同方式受到影響:

let percent = $$"""50% of 20 is %%.1f{{20m * 0.5m}}"""
// "50% of 20 is 10.0"

另請參閱