CodeBlanks Logo Icon CodeBlanks

Summary - Data types

Combine different types to build a grade-calculating program.

Data types summary

Scalar types: integers (i8…i128, u8…u128, isize/usize), decimals (f32, f64), bool and char (4-byte Unicode). Compound types: tuples (T1, T2) and arrays [T; N]. Conversions between types are explicit with as; for overflow there are the checked_*/wrapping_*/saturating_* methods.

Safe conversion

as truncates silently; to check whether a value fits, use TryFrom:

let buyuk: i32 = 300;
match u8::try_from(buyuk) {
    Ok(v) => println!("sığdı: {v}"),
    Err(e) => println!("sığmadı: {e}"),
}

For lossless conversions there are From/into: let x: i64 = 5_i32.into();.

Practice Conversion comparison

For let n: i32 = 300;, print the result of n as u8 and of u8::try_from(n).is_err() with println!("{} {}", ...).

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let n: i32 = 300;
    println!("{} {}", n as u8, u8::try_from(n).is_err());
}

Expected output

44 true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is <code>300 as u8</code>?

  • 44 Correct answer
  • 255
  • A compile error
  • 300

Explanation: as truncates the high bits in an integer conversion: 300 - 256 = 44. For a safe conversion, u8::try_from(300) returns an error.

2 Lossless conversion

Question
let kucuk: i32 = 5;
let buyuk: i64 = kucuk.____();
Answer
let kucuk: i32 = 5;
let buyuk: i64 = kucuk.into();

Explanation: into converts losslessly between types that implement From.

3 Group summary

Term Meaning
i32 / f64 Default number types
char 4-byte Unicode
(T1, T2) Tuple
[T; N] Fixed-length array

All lessons in Beginner