รวมตัวแปร Variable Bindings
ภาษา Rust มีที่มาจากภาษา C/C++ ซึ่งเป็นภาษาเก่าแก่ที่ยังเป็นที่นิยมมาถึงปัจจุบันนี้ ทำให้เราได้เห็นการรวมตัวแปรหรือรวมคำสั่งในภาษา Rust เหมือนภาษา C/C++ อีกด้วย ตัวอย่าง
ในหลาย ๆ ภาษานี้เรียกว่าตัวแปร แต่ในภาษา Rust เราสามารถกำหนดค่าตัวแปรได้เหมือนกับการจับคู่ และแสดงค่าตัวแปรออกมาเต็มรูปแบบ เช่น
และเราสามารถเพิ่มชนิดให้กับตัวแปรถ้าเราต้องการ แต่ชนิดของตัวแปรต้องตามหลัง colon (:):
ในอนาคตเราอาจใส่คำอธิบายชนิดในความคิดเห็นได้ดังนี้
ถ้าเราต้องการที่จะมีผลผูกพันที่เปลี่ยนแปลงได้คุณสามารถใช้ mut:
เมื่อเราเอามาใช้งานกับคำสั่ง println! โดยแก้ไขไฟล์ helloworld.rs ในบทความที่แล้วจะได้
เมื่อสั่ง Build จะได้ผลลัพธ์ดังนี้
ขอบคุณครับ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let x = 5; | |
} |
ในหลาย ๆ ภาษานี้เรียกว่าตัวแปร แต่ในภาษา Rust เราสามารถกำหนดค่าตัวแปรได้เหมือนกับการจับคู่ และแสดงค่าตัวแปรออกมาเต็มรูปแบบ เช่น
let (x, y) = (1, 2);เรากำหนดให้ x มี 1 y มี 2
และเราสามารถเพิ่มชนิดให้กับตัวแปรถ้าเราต้องการ แต่ชนิดของตัวแปรต้องตามหลัง colon (:):
let x: i32 = 5;มีความหมายว่า "5 เป็นค่าของชนิด i32 ของตัวแปร x" โดย i32 ก็คือ จำนวนบิตที่จะเก็บ 32 บิตของ signed integers
ในอนาคตเราอาจใส่คำอธิบายชนิดในความคิดเห็นได้ดังนี้
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let x = 5; // x: i32 | |
} |
let mut x = 5; // mut x: i32หากเราต้องการประกาศตัวแปรเป็นจำนวนเต็ม
x = 10;
let x: int = 10;ตัวแปร x จะมีค่าเท่ากับ 10
เมื่อเราเอามาใช้งานกับคำสั่ง println! โดยแก้ไขไฟล์ helloworld.rs ในบทความที่แล้วจะได้
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let x: i32; | |
println!("The value of x is: {}", x); | |
} |
$ cargo buildจะพบกับข้อผิดพลาดและไม่สามารถ Build ในการรวมตัวแปรเพื่อใช้งานกับคำสั่ง println! จะกล่าวในบทความต่อไปครับ
Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
src/main.rs:4 println!("The value of x is: {}", x);
^
note: in expansion of format_args!
<std macros>:2:23: 2:77 note: expansion site
<std macros>:1:1: 3:2 note: in expansion of println!
src/main.rs:4:5: 4:42 note: expansion site
error: aborting due to previous error
Could not compile `helloworld`.
ขอบคุณครับ
ความคิดเห็น
แสดงความคิดเห็น