Pular para o conteúdo

Faixas e Spread

Nesta página

As faixas .. e ..= geram sequências de inteiros. A forma exclusiva start..end vai até end - 1; a inclusiva start..=end inclui o último valor. Faixas podem ser usadas em for, armazenadas em variáveis e usadas para fatiar arrays e strings.

Faixas exclusiva e inclusiva em for, armazenamento em variável e fatiamento de array.

09-ranges.zolo
Playground
// Feature: Range operators `..` (exclusive) and `..=` (inclusive)

// Syntax: `start..end` (up to end-1) and `start..=end` (up to end)

// When to use: generate sequences for `for`, slice arrays/strings.

// Same semantics as Rust and Python (but Python only has `..` via

// `range`).


// Exclusive range — does not include the end.

for i in 0..5 {
  print(i)
}

// expected: 0, 1, 2, 3, 4


print("---")

// Inclusive range — includes the end.

for i in 0..=3 {
  print(i)
}

// expected: 0, 1, 2, 3


print("---")

// Range can be stored in a variable.

let r = 1..=5
var total = 0
for i in r { total = total + i }
print(total)  // 15


// Slicing an array with a range.

let arr = [10, 20, 30, 40, 50]
print(arr[1..3])  // [20, 30] (indices 1 and 2)

print(arr[2..=4])  // [30, 40, 50]


// Counting down: use stdlib (not native). Workaround:

var down = []
for i in 0..5 {
  let v = 4 - i
  down = [...down, v]
}
print(down)  // [4, 3, 2, 1, 0]


// Range size.

var count = 0
for _ in 0..100 { count = count + 1 }
print(count)  // 100

O operador spread ... expande um array dentro de um literal de array. É a forma idiomática de concatenar arrays ou inserir elementos no meio de uma sequência. Use também em parâmetros de função do tipo ...T para funções variádicas.

A cópia com alteração de uma struct é um recurso separado e usa dois pontos: User { name: "Bob", ..alice }. Campos nomeados vencem os campos copiados. Não escreva { ...alice }: chaves sem um nome de tipo formam um bloco, enquanto literais de mapa começam com #{.

Concatenação com [...a, ...b], cópia rasa e parâmetro variádico ...int.

10-spread.zolo
Playground
// Feature: Spread `...` in array literals

// Syntax: `[...a, ...b]` in array literal (concatenates)

// When to use: copy and/or concatenate arrays without calling

// functions. Important restrictions:

//   - Only works in array literals.

//   - Does NOT work in destructuring (`let (h, ...t) = ...`).

//   - Does NOT work in calls (`f(...arr)` is an error).

//   - For varargs in functions, use `...` on the parameter TYPE.


// Concatenate two arrays.

let a = [1, 2, 3]
let b = [4, 5]
let c = [...a, ...b]
print(c)  // [1, 2, 3, 4, 5]


// Insert elements between spreads.

let d = [0, ...a, 99, ...b, 100]
print(d)  // [0, 1, 2, 3, 99, 4, 5, 100]


// Shallow copy — `[...arr]` creates a new array.

let original = [10, 20, 30]
var copy = [...original]
copy.push(40)
print(original)  // [10, 20, 30] (intact)

print(copy)  // [10, 20, 30, 40]


// Spread applies to any array-shaped expression.

fn make_seq(n: int) -> [int] {
  var result = []
  for i in 0..n { result = [...result, i] }
  return result
}

let combined = [-1, ...make_seq(3), -2]
print(combined)  // [-1, 0, 1, 2, -2]


// Varargs (related topic): `...` goes ON THE TYPE of the parameter.

fn sum_all(nums: ...int) -> int {
  var total = 0
  for n in nums { total = total + n }
  return total
}

print(sum_all(1, 2, 3, 4, 5))  // 15

print(sum_all())  // 0

Desafio

Crie dois arrays quaisquer e un-os com spread, inserindo o número 0 exatamente no meio. Verifique que os arrays originais não foram modificados.

Buscar no Zolo

9 resultados

enespt-br