Saltar al contenido

10 · Strings

Concatenación e Interpolación

El operador + para unir strings y la sintaxis {expr} para incrustar valores.

En esta página

El operador + une strings. Para concatenar un número, conviértelo primero con tostring:

+ para unir piezas; tostring para convertir números.

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

En la mayoría de los casos la interpolación es más legible. Cualquier expresión dentro de {} se evalúa y se incrusta en la string — sin +, sin conversiones explícitas:

"{expr}" acepta variables, operaciones, llamadas a métodos y acceso a campos.

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!

Desafío

Crea un struct Producto con campos nombre: str y precio: float. Imprime una línea usando interpolación con el estilo "Nombre: {nombre} — $ {precio:.2f}".

Índice global

Encuentra tu camino por Zolo

Prueba una idea

Empieza aquí

9 resultados

9 resultados

enespt-br