Skip to content

Concatenation and Interpolation

The + operator joins strings. To concatenate a number, convert it first with tostring:

+ to join pieces; tostring to convert numbers.

02-concatenation.zolo
Playground
// Feature: String concatenation

// Syntax: `"a" + "b"` (operator `+`)

// When to use: join fixed pieces. For variables, prefer interpolation (03).


let name = "Alice"
let greeting = "Hello, " + name + "!"
print(greeting)

// expected: Hello, Alice!


// Chained concatenation.

let first = "Good"
let second = "morning"
let third = "!"
print(first + " " + second + third)

// expected: Good morning!


// Concatenating with numbers — convert with `tostring` first.

let age = 30
print("age: " + tostring(age))

// expected: age: 30


// Empty string as accumulator.

var acc = ""
for piece in ["a", "b", "c"] {
  acc = acc + piece
}
print(acc)

// expected: abc


// When the result depends heavily on variables, prefer interpolation:

print("Name: {name}, age: {age}")
// expected: Name: Alice, age: 30

In most cases interpolation is more readable. Any expression inside {} is evaluated and embedded in the string — no +, no explicit conversions:

"{expr}" accepts variables, operations, method calls, and field access.

03-interpolation.zolo
Playground
// Feature: String interpolation
// Syntax: `"text {expr} more text"`
// When to use: format with variables without raw `+`.

let name = "Alice"
let age = 30
print("{name} is {age} years old")

// expected: Alice is 30 years old

// Arbitrary expressions inside `{}`.
print("double the age: {age * 2}")
// expected: double the age: 60
print("of legal age? {age >= 18}")

// expected: of legal age? true

// Function/method calls inside interpolation.
let text = "hello"
print("upper: {text.upper()}")

// expected: upper: HELLO

// Struct field access.
struct User {
  name: str,
  role: str,
}

let u = User { name: "Bob", role: "admin" }
print("{u.name} ({u.role})")

// expected: Bob (admin)

// Array / map item access.
let fruits = ["apple", "banana", "grape"]
print("first fruit: {fruits[0]}")

// expected: first fruit: apple

// Simple nesting — internal concatenation works.
let greeting = "Hello"
print("{greeting + ", " + name}!")
// expected: Hello, Alice!

Challenge

Create a Product struct with fields name: str and price: float. Print a line using interpolation in the style "Name: {name} — $${price:.2f}".

enespt-br