← 講座に戻る: Rust from scratch

Scalar types and week 1 review

動画は近日公開

Rust is a statically typed language: every value has a type known at compile time. Usually you do not have to write it, because the compiler infers it, but you should know the basic types. They are called scalar because they represent a single value: integers, floating-point numbers, booleans and characters. In this lesson you will see each one, how to convert between them and what happens when a number does not fit its type. At the end we review all of week 1.

Integers

Integers are either signed (i8, i16, i32, i64, i128, isize) or unsigned (u8, u16, u32, u64, u128, usize). The number is the amount of bits: a u8 stores 0 to 255 and an i8 stores -128 to 127. If you say nothing, Rust uses i32. The isize and usize types depend on the architecture (64 bits on most computers) and are used mainly for indexes and sizes. You can write literals with underscores to read them better, in hexadecimal (0xff), octal (0o77), binary (0b1010) or as a byte (b'A').

rust
fn main() {
    let a: u8 = 255;
    let b = 1_000_000;      // i32 by default
    let c = 0xff;           // 255
    let d = 0b1010;         // 10
    let e: i64 = -42;
    let size: usize = 7;
    println!("{a} {b} {c} {d} {e} {size}");
    println!("u8 max = {}, i8 min = {}", u8::MAX, i8::MIN);
}

Overflow

What happens if you add 1 to a u8 that holds 255? In debug mode the program panics (it stops with a message); in release mode the number "wraps around" to 0 silently. Since that difference is dangerous, the standard library gives you methods to choose the behavior: wrapping_add wraps, checked_add returns an Option (None on overflow), saturating_add stays at the maximum and overflowing_add returns the result together with a flag. Choose the one that states your intention.

rust
fn main() {
    let x: u8 = 250;
    println!("{}", x.wrapping_add(10));      // wraps around
    println!("{:?}", x.checked_add(10));     // None
    println!("{:?}", x.checked_add(5));      // Some(255)
    println!("{}", x.saturating_add(10));    // stays at max
    println!("{:?}", x.overflowing_add(10)); // (result, overflowed)
}

Floats, booleans and characters

There are two floating-point types: f32 and f64; the default is f64. Booleans (bool) are true or false and are the result of comparisons. The char type holds a Unicode scalar value, takes 4 bytes and is written with single quotes: 'a', 'ñ', '日' or an emoji. Do not confuse it with "a", which is a text string. Rust does not convert numeric types automatically: adding an i32 to an f64 is a compile error. To convert you use as, and you must know that as can truncate data (300 as u8 becomes 44, 3.9 as i32 becomes 3).

rust
fn main() {
    let pi = 3.14159;           // f64
    let half: f32 = 0.5;
    let is_big = 10 > 3;        // bool
    let letter = 'ñ';
    let heart = '❤';
    println!("{pi} {half} {is_big} {letter} {heart}");

    let n: i32 = 7;
    let avg = n as f64 / 2.0;   // 3.5
    let cut = 3.9_f64 as i32;   // 3
    let wrapped = 300_i32 as u8; // 44
    println!("{avg} {cut} {wrapped}");
    println!("{}", 'a' as u32); // 97
}

Week 1 review

  • You install with rustup; rustc compiles one file, cargo manages projects (cargo new, build, run, check).
  • Variables are immutable by default; mut allows changes; const requires a type and a fixed value; shadowing creates a new variable with the same name.
  • The scalar types are integers, floats, bool and char; conversions use as and are explicit.
  • Overflow is controlled with wrapping_, checked_ and saturating_.
rust
const FREEZING_F: f64 = 32.0;

fn main() {
    let celsius: i32 = 25;
    let fahrenheit = celsius as f64 * 9.0 / 5.0 + FREEZING_F;
    println!("{celsius} C = {fahrenheit} F");

    let small: u8 = 200;
    println!("{:?}", small.checked_add(100));
}

理解度チェック

問題 1 / 6

Which integer type does Rust use by default?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →