Pular para o conteúdo

Concatenação e Interpolação

Nesta página

O operador + junta strings. Para concatenar um número, converta antes com tostring:

+ para unir pedaços; tostring para converter 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

Na maioria dos casos, a interpolação é mais legível. Qualquer expressão dentro de {} é avaliada e embutida na string — sem +, sem conversões explícitas:

"{expr}" aceita variáveis, operações, chamadas de método e acesso 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!

Desafio

Crie um struct Produto com campos nome: str e preco: float. Imprima uma linha usando interpolação no estilo "Nome: {nome} — R$ {preco:.2f}".

Buscar no Zolo

9 resultados

enespt-br