ประเภทข้อมูล (Data Types) และ Control Flow ใน Rust

Sharing is caring!

Rust เป็นภาษา statically typed ซึ่งหมายความว่า type ของค่าทุกตัวจะต้องรู้ตั้งแต่ตอน compile-time ในบทความนี้เราจะมาเรียนรู้เกี่ยวกับประเภทข้อมูล (Data Types) และ control flow ที่ใช้ในการเขียนโปรแกรมในภาษา Rust

1. Primitive Data Types

1.1 Scalar Types

  • Integers: i8, i16, i32, i64, i128, isize
  • Unsigned: u8, u16, u32, u64, u128, usize
  • Floating-point: f32, f64
  • Boolean: true, false
  • Character: ใช้ single quotes เช่น ‘a’
fn main() {
    let x: i32 = 10;
    let pi: f64 = 3.1415;
    let is_rust_fun: bool = true;
    let letter: char = 'R';
}

1.2 Compound Types

  • Tuple: กลุ่มของค่าหลายประเภท เช่น let tup = (1, true, 'a');
  • Array: กลุ่มของค่าชนิดเดียวกัน เช่น let arr = [1, 2, 3];
fn main() {
    let tup: (i32, bool, char) = (42, false, 'z');
    let (a, b, c) = tup;
    println!("{} {} {}", a, b, c);

    let arr = [10, 20, 30];
    println!("{}", arr[1]);
}

2. Type Inference และ Mutability

Rust สามารถ infer type ได้จากค่าที่กำหนด

fn main() {
    let x = 5; // Rust จะเข้าใจว่า x คือ i32
    let mut y = 10; // y สามารถเปลี่ยนค่าได้
    y += 1;
    println!("{}", y);
}

3. Control Flow (การควบคุมทิศทางของโปรแกรม)

3.1 if/else

fn main() {
    let age = 18;
    if age >= 18 {
        println!("เป็นผู้ใหญ่");
    } else {
        println!("ยังไม่บรรลุนิติภาวะ");
    }
}

3.2 if เป็น expression

fn main() {
    let score = 85;
    let grade = if score >= 80 { "A" } else { "B" };
    println!("{}", grade);
}

3.3 match (เหมือน switch)

fn main() {
    let day = 3;
    match day {
        1 => println!("จันทร์"),
        2 => println!("อังคาร"),
        3 => println!("พุธ"),
        _ => println!("วันอื่น"),
    }
}

3.4 loop

fn main() {
    let mut count = 0;
    loop {
        println!("count: {}", count);
        count += 1;
        if count >= 3 {
            break;
        }
    }
}

3.5 while

fn main() {
    let mut n = 5;
    while n > 0 {
        println!("{}", n);
        n -= 1;
    }
}

3.6 for

fn main() {
    for i in 1..=5 {
        println!("รอบที่ {}", i);
    }
}

4. Option และ Result

Rust ไม่มี null แต่มี Option และ Result เป็น enum

fn divide(x: f64, y: f64) -> Option {
    if y == 0.0 {
        None
    } else {
        Some(x / y)
    }
}

fn main() {
    match divide(10.0, 2.0) {
        Some(result) => println!("ผลลัพธ์: {}", result),
        None => println!("หารด้วยศูนย์ไม่ได้"),
    }
}

5. Flowchart ภาพรวม

Rust Flow Chart

สรุป

การเข้าใจ Data Types และ Control Flow ใน Rust เป็นจุดเริ่มต้นสำคัญในการพัฒนาโปรแกรม Rust ที่มีคุณภาพ หวังว่าบทความนี้จะช่วยให้คุณเข้าใจพื้นฐานเหล่านี้ได้ง่ายขึ้น


📌 คำค้น SEO

rust data types, rust control flow, rust if else, rust match, rust for loop, rust array tuple, rust primitive type, rust flow statement, rust ภาษาไทย, rust เรียนพื้นฐาน

เผยแพร่โดย poolsawat.com

Leave a Reply

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *