Compartilhamento de tecnologia

[Rust] Aprendizagem do tipo String String

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

O que é corda

  • Existe apenas um tipo String na linguagem principal do Rust, que é String slice.strgeralmente considerado como&stremprestado.
  • O tipo String é fornecido por meio da biblioteca padrão, em vez de ser codificado diretamente na linguagem principal. É um tipo codificado em UTF-8, ampliável e mutável.
  • streStringTodos são codificados em utf-8.

Criar nova String

  • Na verdade, String é implementada envolvendo um vetor do tipo bytes.
  • Crie uma String usando o novo método:let mut s = String::new()
  • Crie uma String usando o método to_string:
    let data = "initial contents";
    let s = data.to_string();
    let s = "initial contents".to_string();
    
    • 1
    • 2
    • 3
  • Crie uma string usando o método String::from,let s = String::from("initial contents").

String de atualização

Anexar string usando push_str e push

let mut s = String::from("foo");
s.push_str("bar");
// s is foobar
  • 1
  • 2
  • 3

push_strO método não altera a propriedade da string

let mut s = String::from("lo");
s.push('l');
// s is lol
  • 1
  • 2
  • 3

Use o operador + ou a macro format para concatenar strings.

let s1 = String::from("Hello, ");
let s2 = String::from("world!");
let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
  • 1
  • 2
  • 3
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");

let s = format!("{s1}-{s2}-{s3}");
  • 1
  • 2
  • 3
  • 4
  • 5

Rust não permite assinaturas para acessar caracteres individuais dentro de uma string

Como iterar sobre uma string

  • Caracteres UniCode individuais podem ser acessados ​​usando o método chars. Use o método bytes para acessar cada byte.
for c in "Зд".chars() {
    println!("{c}");
}
  • 1
  • 2
  • 3