nix-book/source/nix-language/strings.adoc
Amy de Buitléir e4413f09fb temp
2025-09-13 20:10:33 +01:00

81 lines
1.6 KiB
Text

= String operations
== String concatenation
String concatenation uses the `+` operator.
[source]
....
nix-repl> "Hello, " + "world!"
"Hello, world!"
....
== String interpolation
You can use the `${_variable_}` syntax to insert the value of a variable within a string.
[source]
....
nix-repl> name = "Wombat"
nix-repl> "Hi, I'm ${name}."
"Hi, I'm Wombat."
....
[IMPORTANT]
====
You cannot mix numbers and strings.
Earlier we set `a = 7`, so the following expression fails.
[source]
....
nix-repl> "My favourite number is ${a}."
error:
… while evaluating a path segment
at «string»:1:25:
1| "My favourite number is ${a}."
| ^
error: cannot coerce an integer to a string
....
Nix does provide functions for converting between types; we'll see these in the
<<#convert-to-string,next section>>.
====
== Useful built-in functions for strings
Nix provides some built-in functions for working with strings;
a few examples are shown below.
For more information on these and other built-in functions, see the Nix Manual
(https://nixos.org/manual/nix/stable/language/builtins).
How long is this string?
[source]
....
nix-repl> builtins.stringLength "supercalifragilisticexpialidocious"
34
....
Given a starting position and a length, extract a substring.
The first character of a string has index `0`.
[source]
....
nix-repl> builtins.substring 3 6 "hayneedlestack"
"needle"
....
[#convert-to-string]
Convert an expression to a string.
[source]
....
nix-repl> builtins.toString 7
"7"
nix-repl> builtins.toString (3*4 + 1)
"13"
....