0Pricing
Learn Rust Coding · Aula

Tipos de Dados Primitivos e Operadores

Explore os tipos de dados primitivos integrados do Rust, como inteiros, números de ponto flutuante, booleanos e caracteres, juntamente com operadores comuns.

Tipos de Dados Primitivos e Operadores é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 2 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 3 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Intro to Primitive Data Types

Welcome to a foundational lesson in Rust! Today, we'll explore primitive data types and basic operators.

Primitive types are the most fundamental building blocks for storing data. They represent simple values like numbers, true/false, or single characters.

Understanding these types is crucial for writing efficient and correct Rust code.

Rust's Integer Types

Rust provides various integer types to fit different needs. They come in two main flavors:

  • Signed Integers (i prefix): Can store both positive and negative numbers (e.g., i8, i32, i64).
  • Unsigned Integers (u prefix): Can only store positive numbers or zero (e.g., u8, u32, u64).

The number indicates the bits of storage, e.g., i32 is a 32-bit signed integer. isize and usize are pointer-sized integers, adapting to your system's architecture (32-bit or 64-bit).

Declaring Integer Variables

Let's see how to declare and use integer types in Rust. Notice how we can explicitly add a type annotation or let Rust infer it.

Try running this example:

fn main() {
  let signed_val: i32 = -100;
  let unsigned_val: u32 = 250;
  let inferred_int = 500; // Rust infers i32 by default
  let big_unsigned: u64 = 1_000_000_000;

  println!("Signed: {}", signed_val);
  println!("Unsigned: {}", unsigned_val);
  println!("Inferred: {}", inferred_int);
  println!("Big Unsigned: {}", big_unsigned);
}

Floating-Point Numbers

For numbers with decimal points, Rust offers floating-point types:

  • f32: Single-precision float (32-bit).
  • f64: Double-precision float (64-bit). This is the default floating-point type in Rust.

f64 is generally preferred for most applications due to its higher precision, unless you have specific memory or performance constraints.

Declaring Float Variables

Here's how to declare floating-point numbers. Notice that Rust defaults to f64 if you don't specify a type.

Try running this example:

fn main() {
  let pi: f32 = 3.14159;
  let e = 2.718281828; // Inferred as f64
  let temperature: f64 = 98.6;

  println!("Pi (f32): {}", pi);
  println!("E (f64 inferred): {}", e);
  println!("Temperature (f64): {}", temperature);
}

Booleans and Characters

Beyond numbers, Rust has types for logical values and single letters:

  • bool: Represents a truth value, either true or false.
  • char: Represents a single Unicode scalar value. This means a char can be more than just ASCII – it can be any letter, emoji, or symbol.

A char uses 4 bytes of memory, ensuring it can store any Unicode character.

Bools and Chars in Action

Let's declare some boolean and character variables. Notice the single quotes for char values.

Try running this example:

fn main() {
  let is_rust_fun: bool = true;
  let has_errors = false; // Inferred as bool
  let first_letter: char = 'R';
  let emoji_char: char = '🚀';

  println!("Is Rust fun? {}", is_rust_fun);
  println!("Has errors? {}", has_errors);
  println!("First letter: {}", first_letter);
  println!("Emoji: {}", emoji_char);
}

Basic Arithmetic Operators

Just like in math, Rust uses operators to perform calculations. Here are the common arithmetic operators:

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • %: Remainder (Modulo)

Remember that integer division (e.g., 10 / 3) will truncate the decimal part, resulting in an integer (3, not 3.33).

Using Arithmetic Operators

Let's put these operators into practice with some numbers. Pay attention to how integer division behaves!

Try running this example:

fn main() {
  let a = 15;
  let b = 4;

  println!("Addition: 15 + 4 = {}", a + b);
  println!("Subtraction: 15 - 4 = {}", a - b);
  println!("Multiplication: 15 * 4 = {}", a * b);
  println!("Integer Division: 15 / 4 = {}", a / b);
  println!("Remainder: 15 % 4 = {}", a % b);

  let x = 15.0;
  let y = 4.0;
  println!("Float Division: 15.0 / 4.0 = {}", x / y);
}

Primitive Types Quiz

Test your understanding of Rust's primitive data types and basic operators.

Recap: Primitives & Operators

Great job! You've learned about Rust's fundamental data types:

  • Integers: i8, u8, i32, u32, etc., for whole numbers.
  • Floats: f32 and f64 for decimal numbers.
  • Booleans: bool for true or false.
  • Characters: char for single Unicode values.

You also explored basic arithmetic operators like +, -, *, /, and %. These are the building blocks for more complex logic in your programs.

Perguntas Frequentes

A aula “Tipos de Dados Primitivos e Operadores” é grátis?

Sim — o texto completo de “Tipos de Dados Primitivos e Operadores” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 3 aulas no total.

O que vou aprender em “Tipos de Dados Primitivos e Operadores”?

Explore os tipos de dados primitivos integrados do Rust, como inteiros, números de ponto flutuante, booleanos e caracteres, juntamente com operadores comuns. Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Learn Rust Coding?

Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 3.

Quanto tempo leva a aula “Tipos de Dados Primitivos e Operadores”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Learn Rust Coding?

Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Variáveis, Mutabilidade e Sombreamento
  2. Tipos de Dados Primitivos e Operadores
  3. Funções e Fluxo de Controlo
← Voltar para Learn Rust Coding