Strings e Formatação em Go — Referência Rápida
Strings em Go são sequências de bytes imutáveis codificadas em UTF-8. Esta referência cobre formatação com fmt, manipulação com strings, conversão com strconv e operações Unicode. Para fundamentos, veja strings no glossário e o cheatsheet de sintaxe básica.
Tabela Completa de fmt Verbs
Valores Gerais
| Verb | Descrição | Exemplo | Saída |
|---|---|---|---|
%v | Valor no formato padrão | fmt.Sprintf("%v", 42) | 42 |
%+v | Struct com nomes de campos | fmt.Sprintf("%+v", p) | {Nome:Ana Idade:30} |
%#v | Representação Go (syntax) | fmt.Sprintf("%#v", p) | main.Pessoa{Nome:"Ana", Idade:30} |
%T | Tipo da variável | fmt.Sprintf("%T", 42) | int |
%% | Literal % | fmt.Sprintf("100%%") | 100% |
Inteiros
| Verb | Descrição | Exemplo | Saída |
|---|---|---|---|
%d | Decimal | fmt.Sprintf("%d", 42) | 42 |
%b | Binário | fmt.Sprintf("%b", 42) | 101010 |
%o | Octal | fmt.Sprintf("%o", 42) | 52 |
%O | Octal com prefixo 0o | fmt.Sprintf("%O", 42) | 0o52 |
%x | Hexadecimal (minúsculo) | fmt.Sprintf("%x", 255) | ff |
%X | Hexadecimal (maiúsculo) | fmt.Sprintf("%X", 255) | FF |
%c | Caractere Unicode | fmt.Sprintf("%c", 65) | A |
%U | Unicode (U+0041) | fmt.Sprintf("%U", 65) | U+0041 |
Floats
| Verb | Descrição | Exemplo | Saída |
|---|---|---|---|
%f | Decimal (padrão) | fmt.Sprintf("%f", 3.14) | 3.140000 |
%.2f | 2 casas decimais | fmt.Sprintf("%.2f", 3.14159) | 3.14 |
%e | Notação científica | fmt.Sprintf("%e", 100000.0) | 1.000000e+05 |
%g | Mais compacto (%e ou %f) | fmt.Sprintf("%g", 3.14) | 3.14 |
Strings e Bytes
| Verb | Descrição | Exemplo | Saída |
|---|---|---|---|
%s | String simples | fmt.Sprintf("%s", "go") | go |
%q | String com aspas | fmt.Sprintf("%q", "go") | "go" |
%x | Hex de cada byte | fmt.Sprintf("%x", "ab") | 6162 |
Largura e Alinhamento
| Padrão | Descrição | Exemplo | Saída |
|---|---|---|---|
%10d | Largura mínima 10, alinhado à direita | fmt.Sprintf("%10d", 42) | 42 |
%-10d | Alinhado à esquerda | fmt.Sprintf("%-10d|", 42) | 42 | |
%010d | Preenchido com zeros | fmt.Sprintf("%010d", 42) | 0000000042 |
%+d | Sempre mostra sinal | fmt.Sprintf("%+d", 42) | +42 |
Veja fmt no glossário para mais contexto.
Pacote strings
Funções Mais Usadas
| Função | Descrição | Exemplo |
|---|---|---|
strings.Contains(s, sub) | Contém substring | strings.Contains("golang", "lang") → true |
strings.HasPrefix(s, pre) | Começa com | strings.HasPrefix("golang", "go") → true |
strings.HasSuffix(s, suf) | Termina com | strings.HasSuffix("main.go", ".go") → true |
strings.Index(s, sub) | Posição da substring | strings.Index("golang", "lang") → 2 |
strings.ToUpper(s) | Maiúsculas | strings.ToUpper("go") → "GO" |
strings.ToLower(s) | Minúsculas | strings.ToLower("GO") → "go" |
strings.TrimSpace(s) | Remove espaços início/fim | strings.TrimSpace(" go ") → "go" |
strings.Trim(s, cut) | Remove caracteres início/fim | strings.Trim("--go--", "-") → "go" |
strings.Replace(s, old, new, n) | Substituir | strings.Replace("aaa", "a", "b", 2) → "bba" |
strings.ReplaceAll(s, old, new) | Substituir tudo | strings.ReplaceAll("aaa", "a", "b") → "bbb" |
strings.Split(s, sep) | Dividir | strings.Split("a,b,c", ",") → ["a","b","c"] |
strings.Join(slice, sep) | Juntar | strings.Join([]string{"a","b"}, "-") → "a-b" |
strings.Count(s, sub) | Contar ocorrências | strings.Count("banana", "a") → 3 |
strings.Repeat(s, n) | Repetir | strings.Repeat("go", 3) → "gogogo" |
strings.Map(f, s) | Transformar cada rune | Personalizado |
strings.Builder (Concatenação Eficiente)
package main
import (
"fmt"
"strings"
)
func main() {
var b strings.Builder
for i := 0; i < 5; i++ {
fmt.Fprintf(&b, "item %d, ", i)
}
fmt.Println(b.String())
}
Dica: nunca concatene strings em loop com
+. Usestrings.Builderoustrings.Join. Isso evita alocações desnecessárias — veja otimização de performance em Go para mais dicas.
strings.NewReader
package main
import (
"fmt"
"io"
"strings"
)
func main() {
r := strings.NewReader("dados de entrada")
buf := make([]byte, 5)
for {
n, err := r.Read(buf)
if err == io.EOF {
break
}
fmt.Print(string(buf[:n]))
}
}
Veja io no glossário para entender a interface Reader/Writer.
Pacote strconv
Conversões entre strings e tipos primitivos.
| Função | Direção | Exemplo |
|---|---|---|
strconv.Itoa(i) | int → string | strconv.Itoa(42) → "42" |
strconv.Atoi(s) | string → int | strconv.Atoi("42") → 42, nil |
strconv.FormatFloat(f, fmt, prec, bits) | float → string | strconv.FormatFloat(3.14, 'f', 2, 64) → "3.14" |
strconv.ParseFloat(s, bits) | string → float | strconv.ParseFloat("3.14", 64) → 3.14, nil |
strconv.FormatBool(b) | bool → string | strconv.FormatBool(true) → "true" |
strconv.ParseBool(s) | string → bool | strconv.ParseBool("true") → true, nil |
strconv.FormatInt(i, base) | int64 → string (base) | strconv.FormatInt(255, 16) → "ff" |
strconv.ParseInt(s, base, bits) | string → int64 | strconv.ParseInt("ff", 16, 64) → 255, nil |
package main
import (
"fmt"
"strconv"
)
func main() {
// int <-> string
s := strconv.Itoa(42)
n, err := strconv.Atoi("42")
if err != nil {
fmt.Println("erro:", err)
return
}
// float <-> string
fs := strconv.FormatFloat(3.14159, 'f', 2, 64)
f, err := strconv.ParseFloat("3.14", 64)
if err != nil {
fmt.Println("erro:", err)
return
}
fmt.Println(s, n, fs, f)
}
Erro comum: usar
string(42)resulta em"*"(caractere Unicode 42), não"42". Usestrconv.Itoaoufmt.Sprintf. Veja cannot use X as type Y para erros de tipo.
Unicode e Runes
Strings em Go são bytes UTF-8. Uma rune é um code point Unicode (int32).
package main
import (
"fmt"
"unicode"
"unicode/utf8"
)
func main() {
s := "Olá, 世界!"
// Contar bytes vs runes
fmt.Println(len(s)) // 14 (bytes)
fmt.Println(utf8.RuneCountInString(s)) // 9 (runes)
// Iterar por runes (correto para UTF-8)
for i, r := range s {
fmt.Printf("byte %d: %c (U+%04X)\n", i, r, r)
}
// Funções unicode
fmt.Println(unicode.IsLetter('A')) // true
fmt.Println(unicode.IsDigit('5')) // true
fmt.Println(unicode.IsSpace(' ')) // true
fmt.Println(unicode.ToUpper('a')) // 65 ('A')
}
| Função | Pacote | Descrição |
|---|---|---|
utf8.RuneCountInString(s) | unicode/utf8 | Contar runes em string |
utf8.ValidString(s) | unicode/utf8 | Verificar UTF-8 válido |
utf8.DecodeRuneInString(s) | unicode/utf8 | Decodificar primeira rune |
unicode.IsLetter(r) | unicode | É letra? |
unicode.IsDigit(r) | unicode | É dígito? |
unicode.IsSpace(r) | unicode | É espaço? |
unicode.ToUpper(r) | unicode | Converter para maiúscula |
unicode.ToLower(r) | unicode | Converter para minúscula |
Dica: use
for _, r := range spara iterar corretamente por caracteres UTF-8.for i := 0; i < len(s); i++itera por bytes.
Padrões com fmt
Sprintf (Formatar sem Imprimir)
package main
import "fmt"
func main() {
nome := "Go"
versao := 1.26
msg := fmt.Sprintf("Linguagem: %s, versão: %.1f", nome, versao)
fmt.Println(msg) // Linguagem: Go, versão: 1.3
}
Fprintf (Escrever em Writer)
package main
import (
"fmt"
"os"
)
func main() {
fmt.Fprintf(os.Stderr, "erro: %s\n", "arquivo não encontrado")
}
Tabela de Funções fmt
| Função | Destino | Retorno |
|---|---|---|
fmt.Print(...) | stdout | — |
fmt.Println(...) | stdout + newline | — |
fmt.Printf(format, ...) | stdout formatado | — |
fmt.Sprint(...) | string | string |
fmt.Sprintf(format, ...) | string formatada | string |
fmt.Fprint(w, ...) | io.Writer | — |
fmt.Fprintf(w, format, ...) | io.Writer formatado | — |
fmt.Errorf(format, ...) | error | error (wrapping com %w) |
fmt.Errorf com %w é essencial para o tratamento de erros em Go — permite wrapping de erros para uso com errors.Is e errors.As.
Expressões Regulares (regexp)
package main
import (
"fmt"
"regexp"
)
func main() {
// Compilar (verifica sintaxe; use MustCompile para panic on error)
re := regexp.MustCompile(`\d{3}\.\d{3}\.\d{3}-\d{2}`)
// Match
fmt.Println(re.MatchString("123.456.789-00")) // true
// Find
fmt.Println(re.FindString("CPF: 123.456.789-00 aqui"))
// FindAll
texto := "tel: 011-1234 e 021-5678"
retel := regexp.MustCompile(`\d{3}-\d{4}`)
fmt.Println(retel.FindAllString(texto, -1))
// Replace
limpo := re.ReplaceAllString("CPF: 123.456.789-00", "***")
fmt.Println(limpo)
}
| Método | Descrição |
|---|---|
MatchString(s) | Retorna bool |
FindString(s) | Primeira ocorrência |
FindAllString(s, n) | Todas as ocorrências (n=-1 para todas) |
ReplaceAllString(s, repl) | Substituir todas |
Split(s, n) | Dividir por padrão |
Logging com slog
Para logging estruturado, Go 1.21+ oferece o pacote log/slog. Veja o guia de slog para uso completo.
package main
import "log/slog"
func main() {
slog.Info("servidor iniciado", "porta", 8080)
slog.Warn("cache expirado", "ttl", "5m")
slog.Error("falha na conexão", "err", "timeout")
}
Para comparar formatação de strings entre linguagens, veja como Python usa f-strings e format(), e como Rust implementa formatação com a macro format!.
Veja Também
- Cheatsheet: Sintaxe Básica — Tipos, variáveis e funções
- Cheatsheet: Slices, Maps e Structs — Estruturas de dados
- Cheatsheet: Testes e Debug — Testing e profiling
- Cheatsheet: Concorrência — Goroutines e channels
- Tratamento de Erros — Padrões de error handling com fmt.Errorf
- Glossário: string — Conceitos de strings em Go