Pular para o conteúdo
Nesta página

Strings

Literais de String

let greeting = "Hello, World!"
let single = "It's a string"

Interpolação de Strings

Incorpore expressões dentro de strings usando {}:

let name = "Zolo"
let msg = "Hello, {name}!"          // "Hello, Zolo!"

let x = 10
let y = 20
let sum = "{x} + {y} = {x + y}"    // "10 + 20 = 30"

Expressões na Interpolação

Qualquer expressão pode ser colocada dentro de {}:

let items = [1, 2, 3]
print("Count: {Array.len(items)}")      // "Count: 3"
print("Double: {items[0] * 2}")         // "Double: 2"
print("Greeting: {if loud { "HI!" } else { "hi" }}")

Interpolação Aninhada

Expressões interpoladas podem conter suas próprias strings:

let result = "User: {get_user("admin").name}"

Strings Multilinhas

Use aspas triplas """ para strings multilinhas:

let text = """
    This is a
    multiline string
    with indentation preserved
"""

Templates com Tag

Templates com tag permitem que você prefixe uma string com um nome de tag, habilitando sintaxe semelhante a DSL:

let id = 42
let query = sql"SELECT * FROM users WHERE id = {id}"

let title = "Hello"
let page = html"<h1>{title}</h1>"

Como Templates com Tag Funcionam

Um template com tag tag"text {expr} more" compila para uma chamada de função:

// sql"SELECT * FROM users WHERE id = {id}"
// compiles to:
sql({"SELECT * FROM users WHERE id = ", ""}, id)

A função de tag recebe:

  1. Uma tabela de partes de string literal
  2. Os valores de expressão interpolados como argumentos adicionais

Definindo Funções de Tag

fn sql(parts: [str], id: int) -> str {
    "{parts[0]}{id}{parts[1]}"
}

fn html(parts: [str], content: str) -> str {
    "{parts[0]}{content}{parts[1]}"
}

Templates com Tag Simples

Templates com tag sem interpolação:

let regex = re"^\d+$"      // re({"^\\d+$"})
let path = raw"C:\Users"    // raw({"C:\\Users"})

Operações com Strings

A biblioteca padrão fornece utilitários para strings:

// Trimming
string.trim("  hello  ")        // "hello"
string.trim_start("  hello")    // "hello"
string.trim_end("hello  ")      // "hello"

// Checking
string.starts_with("hello", "he")   // true
string.ends_with("hello", "lo")     // true
string.contains("hello", "ell")     // true
string.is_empty("")                 // true

// Transforming
string.split("a,b,c", ",")         // ["a", "b", "c"]
string.replace("hello", "l", "r")  // "herro"
string.chars("hello")              // ["h", "e", "l", "l", "o"]

// Padding
string.pad_start("42", 5, "0")     // "00042"
string.pad_end("hi", 5, ".")       // "hi..."

Veja Biblioteca Padrão para a API completa.

Buscar no Zolo

9 resultados

enespt-br