fn main() { // The function declaration is not indented
// First step in function body
// Substep: execute before First step can be complete
// Second step in function body
// Substep A: execute before Second step can be complete
// Substep B: execute before Second step can be complete
// Sub-substep 1: execute before Substep B can be complete
// Third step in function body, and so on...
}
println!("The first letter of the English alphabet is {} and the last letter is {}.", 'A', 'Z');
fn main() {
println!("{}{{}}", 1);
}
let a_number;
let a_word = "Ten";
a_number = 10;
a_number = 15; // エラー
let mut a_number = 10;
a_number = 15;
let shadow_num = 5;
let shadow_num = shadow_num + 5;
let number: u32 = 14;
let number: u32 = "14"; // コンパイルエラー
let number_64 = 4.0;
let number_32: f32 = 5.0;
let is_bigger = 1 > 4;
let tuple_e = ('e', 5i32, true);
if 1 == 2 {
println!("True, the numbers are equal."); //
} else {
println!("False, the numbers are not equal.");
}
let formal = true;
let greeting = if formal { // if used here as an expression
"Good day to you." // return a String
} else {
"Hey!" // return a String
};
let num = 500 // num variable can be set at some point in the program
let out_of_range: bool;
if num < 0 {
out_of_range = true;
} else if num == 0 {
out_of_range = true;
} else if num > 512 {
out_of_range = true;
} else {
out_of_range = false;
}
// Classic struct with named fields
struct Student { name: String, level: u8, pass: bool }
// Tuple struct with data types only
struct Grades(char, char, char, char, f32);
// Instantiate tuple structs, pass values in same order as types defined
let mark_1 = Grades('A', 'A', 'B', 'A', 3.75);
let mark_2 = Grades('B', 'A', 'A', 'C', 3.25);
enum WebEvent {
// An enum variant can be like a unit struct without fields or data types
WELoad,
// An enum variant can be like a tuple struct with data types but no named fields
WEKeys(String, char),
// An enum variant can be like a classic struct with named fields and their data types
WEClick { x: i64, y: i64 }
}
// Define a tuple struct
struct KeyPress(String, char);
// Define a classic struct
struct MouseClick { x: i64, y: i64 }
// Redefine the enum variants to use the data from the new structs
// Update the page Load variant to have the boolean type
enum WebEvent { WELoad(bool), WEClick(MouseClick), WEKeys(KeyPress) }
let we_load = WebEvent::WELoad(true);
// Instantiate a MouseClick struct and bind the coordinate values
let click = MouseClick { x: 100, y: 250 };
// Set the WEClick variant to use the data in the click struct
let we_click = WebEvent::WEClick(click);
// Instantiate a KeyPress tuple and bind the key values
let keys = KeyPress(String::from("Ctrl+"), 'N');
// Set the WEKeys variant to use the data in the keys tuple
let we_key = WebEvent::WEKeys(keys);
// Define a tuple struct
#[derive(Debug)]
struct KeyPress(String, char);
// Define a classic struct
#[derive(Debug)]
struct MouseClick {
x: i64,
y: i64,
}
// Redefine the enum variants to use the data from the new structs
// Update the page Load variant to have the boolean type
#[derive(Debug)]
enum WebEvent {
WELoad(bool),
WEClick(MouseClick),
WEKeys(KeyPress),
}
fn is_divisible_by(dividend: u32, divisor: u32) {
// If the divisor is zero, stop execution
if divisor == 0 {
println!("\nError! Division by zero is not allowed.");
} else if dividend % divisor > 0 {
println!("\n{} % {} has a remainder of {}.", dividend, divisor, (dividend % divisor));
} else {
println!("\n{} % {} has no remainder.", dividend, divisor);
}
}
fn main() {
is_divisible_by(12, 4);
is_divisible_by(13, 5);
is_divisible_by(14, 0);
}
fn is_zero(input: u8) -> bool {
if input == 0 {
return true;
}
false
}
fn main() {
if is_zero(0) {
println!("The value is zero.");
}
}
// Declare Car struct to describe vehicle with four named fields
struct Car {
color: String,
transmission: Transmission,
convertible: bool,
mileage: u32,
}
#[derive(PartialEq, Debug)]
// Declare enum for Car transmission type
// TO DO: Fix enum definition so code compiles
enum Transmission {
Manual,
SemiAuto,
Automatic,
}
// Build a "Car" by using values from the input arguments
// - Color of car (String)
// - Transmission type (enum value)
// - Convertible (boolean, true if car is a convertible)
fn car_factory(color: String, transmission: Transmission, convertible: bool) -> Car {
// TO DO: Complete "car" declaration to be an instance of a "Car" struct
// Use the values of the input arguments
// All new cars always have zero mileage
Car {
color: color,
transmission: transmission,
convertible: convertible,
mileage: 0,
}
}
fn main() {
// We have orders for three new cars!
// We'll declare a mutable car variable and reuse it for all the cars
let mut car = car_factory(String::from("Red"), Transmission::Manual, false);
println!(
"Car 1 = {}, {:?} transmission, convertible: {}, mileage: {}",
car.color, car.transmission, car.convertible, car.mileage
);
car = car_factory(String::from("Silver"), Transmission::Automatic, true);
println!(
"Car 2 = {}, {:?} transmission, convertible: {}, mileage: {}",
car.color, car.transmission, car.convertible, car.mileage
);
car = car_factory(String::from("Yellow"), Transmission::SemiAuto, false);
println!(
"Car 3 = {}, {:?} transmission, convertible: {}, mileage: {}",
car.color, car.transmission, car.convertible, car.mileage
);
}
// Declare array, initialize all values, compiler infers length = 7
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
// Declare array, first value = "0", length = 5
let bytes = [0; 5];
// Set first day of week
let first = days[0];
// Set second day of week
let second = days[1];
// Set seventh day of week, use wrong index - should be 6
let seventh = days[7]; // コンパイルエラー
// Declare vector, initialize with three values
let three_nums = vec![15, 3, 46];
println!("Initial vector: {:?}", three_nums);
// Declare vector, first value = "0", length = 5
let zeroes = vec![0; 5];
println!("Zeroes: {:?}", zeroes);
// Create empty vector, declare vector mutable so it can grow and shrink
let mut fruit = Vec::new();
// Push values onto end of vector, type changes from generic `T` to String
fruit.push("Apple");
fruit.push("Banana");
fruit.push("Cherry");
println!("Fruits: {:?}", fruit);
fruit.push(1); // コンパイルエラー
// Pop off value at end of vector
// Call pop() method from inside println! macro
println!("Pop off: {:?}", fruit.pop());
println!("Fruits: {:?}", fruit);
// Declare vector, initialize with three values
let mut index_vec = vec![15, 3, 46];
let three = index_vec[1];
println!("Vector: {:?}, three = {}", index_vec, three);
// Access vector with out-of-bounds index
let beyond = index_vec[10];
println!("{}", beyond);
パニックメッセージ
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 10', src/main.rs:7:18
use std::collections::HashMap;
let mut reviews: HashMap<String, String> = HashMap::new();
reviews.insert("Ancient Roman History".to_string(), "Very accurate.".to_string());
reviews.insert("Cooking with Rhubarb".to_string(), "Sweet recipes.".to_string());
reviews.insert("Programming in Rust".to_string(), "Great examples.".to_string());
// Look for a specific review
let book: &str = "Programming in Rust";
println!("\nReview for \'{}\': {:?}", book, reviews.get(book));
結果
Review for 'Programming in Rust': Some("Great examples.")
// Remove book review
let obsolete: &str = "Ancient Roman History";
println!("\n'{}\' removed.", obsolete);
reviews.remove(obsolete);
// Confirm book review removed
println!("\nReview for \'{}\': {:?}", obsolete, reviews.get(obsolete));
結果
'Ancient Roman History' removed.
Review for 'Ancient Roman History': None
let mut counter = 1;
// stop_loop is set when loop stops
let stop_loop = loop {
counter *= 2;
if counter > 100 {
// Stop loop, return counter value
break counter;
}
};
// Loop should break when counter = 128
println!("Break the loop at counter = {}.", stop_loop);
let mut counter = 0;
while counter < 5 {
println!("We loop a while...");
counter = counter + 1;
}