nix-book/source/nix-language/strings.adoc
Amy de Buitléir 96f65dd5a5 expanded
2025-10-12 15:59:19 +01:00

114 lines
2.1 KiB
Text

= String operations
== String comparison
Nix provides the usual lexicographic comparison operations.
[source]
.Example
....
nix-repl> "apple" == "banana" # equality
false
nix-repl> "apple" != "banana" # inequality
true
nix-repl> "apple" < "banana" # comes alphabetically before?
true
nix-repl> "apple" <= "banana" # equal or comes alphabetically before?
true
nix-repl> "apple" > "banana" # comes alphabetically after?
false
nix-repl> "apple" >= "banana" # equal or comes alphabetically after?
false
....
== String concatenation
String concatenation uses the `+` operator.
[source]
.Example
....
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]
.Example
....
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]
.Example
....
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]
.Example
....
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]
.Example
....
nix-repl> builtins.substring 3 6 "hayneedlestack"
"needle"
....
[#convert-to-string]
Convert an expression to a string.
[source]
.Example
....
nix-repl> builtins.toString 7
"7"
nix-repl> builtins.toString (3*4 + 1)
"13"
....