2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rust examples

Last updated at Posted at 2020-05-30

###特にテーマがないですが勉強時に作った実行できるサンプルをここに纏めます。
このサンプルの一部はyoutubeのビデオ「Rust Programming Tutorials」からまねしたものです。
###Rust examples_001

#![allow(unused)]
fn main() {
    let x: Option<u32> = Some(2);
    println!("when x is {:?}",x);
    println!("x.is_some: {:?}",x.is_some());//true
    println!("x.is_none: {:?}",x.is_none());//false
    
    println!();

    let x: Option<u32> = None;
    println!("when x is {:?}",x);
    println!("x.is_some: {:?}",x.is_some());//false
    println!("x.is_none: {:?}",x.is_none());//true
}

###Rust examples_002

#![allow(unused)]
#![feature(option_result_contains)]

fn main() {
    let x: Option<u32> = Some(2);
    println!("when x is {:?}",x);
    println!("x.contains(&2) is {:?}",x.contains(&2));
    
    println!();
    let x: Option<u32> = Some(3);
    println!("when x is {:?}",x);
    println!("x.contains(&2) is {:?}",x.contains(&2));
    
    println!();
    let x: Option<u32> = None;
    println!("when x is {:?}",x);
    println!("x.contains(&2) is {:?}",x.contains(&2));
}

###Rust examples_003

#![allow(unused)]
fn main() {
    let mut counter = Some(0);

    while let Some(i) = counter {
        if i == 10 {
            counter = None;
        } else {
            println!("{}", i);
            counter = Some(i + 1);
        }
    }
}

###Rust examples_004

#![allow(unused)]
fn main() {
    loop {
        println!("hello world forever!");
        break;
    }

    let mut i = 1;
    let mut counter = 0;
    loop {
        println!("2^{} = {}", counter, i);
        if i > 100 {
            break;
        }
        i *= 2;
        counter += 1;
    }
    assert_eq!(i, 128);
}

###Rust examples_005

#![allow(unused)]
fn main() {
    let (mut a, mut b) = (1, 1);
    let result = loop {
        if b > 10 {
            break b;
        }
        let c = a + b;
        a = b;
        b = c;
        println!("{:?}", (a, b));
    };
    // first number in Fibonacci sequence over 10:
    assert_eq!(result, 13);
    println!("{}", result);
}

###Rust examples_006

#![allow(unused)]
fn main() {
    for i in 0..5 {
        println!("{}", i * 2);
    }

    let mut fours = std::iter::repeat(4);
    for i in std::iter::repeat(4) {
        assert_eq!(Some(4), fours.next());
        println!(
            "this repeat {:?} forever if you don't break it.",
            fours.next()
        );
        break;
    }

    'outer: for i in 1..=5 {
        println!("outer iteration (i): {}", i);

        '_inner: for j in 1..=200 {
            println!("    inner iteration (j): {}", j);
            if j >= 3 {
                // breaks from inner loop, let's outer loop continue.
                break;
            }
            if i >= 2 {
                // breaks from outer loop, and directly to "Bye".
                break 'outer;
            }
        }
    }
    println!("Bye.");
}

###Rust examples_007

#![allow(unused)]
fn main() {
    let iterator = 0..5;
    let mut _iter = std::iter::IntoIterator::into_iter(iterator);
    loop {
        println!("{:?}", _iter);
        match _iter.next() {
            Some(loop_variable) => println!("{:?}", _iter),
            None => break,
        }
    }
}

###Rust examples_008

#![allow(unused)]
fn main() {
    let thing1: u8 = 89.0 as u8;
    println!("thing1 as u8 is {:?}", thing1);

    println!("thing1 as char is {:?}", thing1 as char);

    let thing2: f32 = thing1 as f32 + 10.5;
    println!(
        "thing2 is {:?}, but thing2 as u8 is {:?}",
        thing2, thing2 as u8
    );

    println!("false as u8 is {:?}", false as u8);
    println!("true as u8 is {:?}", true as u8);
}

###Rust examples_009

#![allow(unused)]
// Print Odd numbers under 30 with unit <= 5
fn main() {
    'tens: for ten in 0..3 {
        '_units: for unit in 0..=9 {
            if unit % 2 == 0 {
                continue;
            }
            if unit > 5 {
                continue 'tens;
            }
            println!("{}", ten * 10 + unit);
        }
    }
}

###Rust examples_010

  • エラーになるケース
    vec_iter.png

  • 先にiterを利用するとエラーを解消できる

fn main() {
    let animals = vec!["cat", "dog", "mouse"];
    for a in animals.iter() {
        println!("{}", a);
    }
    for a in animals {
        println!("{}", a);
    }
}

###Rust examples_011

  • エラーになるケース(enumのネーミングルール違反)
    name_rule01.png

  • エラーになるケース(match時のルール違反)
    match_error.png

  • 正常ケース

#[allow(dead_code)]
enum Direction {
    Left,
    Right,
    Up,
    Down,
}
fn main() {
    let player_direction: Direction = Direction::Up;
    match player_direction {
        Direction::Up => println!("here is up direction"),
        _ => (),
    }
}

###Rust examples_012

  • エラーになるケース(constのネーミングルール違反)
    const_naming.png
  • vscode大文字⇔小文字転換
    vs_upper_lower_case.png
  • constの値は変更できないエラー
    const_error.png
  • 正常ケース
#[allow(dead_code)]
// #[allow(non_upper_case_globals)]
const MAX_NUMBER: u8 = 20;

fn main() {
    for n in 1..MAX_NUMBER{
        println!("the number is {}",n);
    }
}

###Rust examples_013

  • スコープ(有効範囲)とシャドーイング(同じ変数名で違うタイプで定義する)
fn main() {
    let x = 10;
    {
        let x = 15;
        println!("x inside is {}", x);
    }
    println!("x outside is {}", x);

    let x = "x is a string";
    println!("{}", x);

    let x = true;
    println!("{}", x);
}

###Rust examples_014

  • レファレンスエラー
    ref_error.png
  • 正常ケース
fn main() {
    let mut x = 10;
    println!("{}", x);
    
    let dom = &mut x;
    // let dom = &x;
    *dom += 1;
    println!("{}", dom);
}

###Rust examples_015

fn main() {
    let numbers: [i32; 5] = [1, 2, 3, 4, 5];
    // loop using iter
    for n in numbers.iter() {
        println!("{}", n);
    }

    // loop using index
    for i in 0..numbers.len() {
        println!("the number[{}] is {}", i, numbers[i]);
    }
}

###Rust examples_016

  • dotでfnを呼び出す時に&selfパラメーターを転送必要なし
    impl_err1.png
  • pathでfnを呼び出す時に&selfパラメーターを転送必要である
    impl_err2.png
  • 正常ケース
struct Rectagle {
    width: u32,
    height: u32,
}

impl Rectagle {
    fn print_description(&self) {
        println!("Rectangle: {} x {}", &self.width, &self.height);
    }
}

fn main() {
    let my_rec = Rectagle {
        width: 10,
        height: 5,
    };
    my_rec.print_description();
    Rectagle::print_description(&my_rec);
}

###Rust examples_017

use std::fs::File;
use std::io::prelude::*;
fn main() {
    //相対パス='hello-rocket/info.txt'ですが、実際は'info.txt'です。
    //原因はcargo.tomlファイルのパスはrootとして使っている。
    let mut file = File::open("info.txt").expect("Can not open this file.");

    let mut contents = String::new();
    file.read_to_string(&mut contents)
        .expect("Oops,Can not read this file.");
    println!("{}",contents);
}

###Rust examples_018

use std::fs::File;
use std::io::prelude::*;

fn main() {
    let mut file = File::create("output.txt").expect("Could not create file!");
    file.write_all(b"Welcome to this tutorial.")
        .expect("Cannot write to this file.");
}

###Rust examples_019

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    for argument in args.iter() {
        println!("{}", argument);
    }
}
  • cargo run arg1 arg2の出力結果
    args.png

###Rust examples_020

struct Person {
    name: String,
    age: u8,
}

trait HasVoiceBox {
    fn speak(&self);
    fn can_speak(&self) -> bool;
}

impl HasVoiceBox for Person {
    fn speak(&self) {
        println!("hello,my name is {}.", self.name);
    }

    fn can_speak(&self) -> bool {
        if self.age > 0 {
            return true;
        }
        return false;
    }
}

fn main() {
    let person = Person {
        name: String::from("Bob"),
        age: 41,
    };

    println!("Can {} speak? {}", person.name, person.can_speak());
    person.speak();
}

###Rust examples_021

fn main() {
    let mut input = String::new();

    println!("Hi mate! say something:");

    match std::io::stdin().read_line(&mut input) {
        Ok(_) => {
            println!("Success! You just say: {}", input.to_uppercase());
        }
        Err(e) => {
            println!("Oops! something went wrong: {}", e);
        }
    }
}

###Rust examples_022

use std::collections::HashMap;

fn main() {
    let mut marks = HashMap::new();

    marks.insert("Rust programming", 96);
    marks.insert("web developing", 92);
    marks.insert("UX design", 75);
    marks.insert("Professional computing study", 45);

    // find length of HashMap
    println!("How many subject have you studied? {}", marks.len());
    println!("{:#?}", marks);

    // get a single value
    match marks.get("Web developing") {
        Some(mark) => println!("You got {} for Web Dev!", mark),
        None => println!("You didn't study web developing."),
    }

    //remove a value
    marks.remove("UX design");
    println!("{:#?}", marks);

    // for loop through HashMap
    for (subject, mark) in &marks {
        println!("{}'s mark is:{}", subject, mark);
    }

    // check for value
    println!(
        "Did you study C++? {}",
        marks.contains_key("C++ Programming")
    );
}

###Rust examples_023

Cargo.toml
[dependencies]
rand = "*"
extern crate rand;
use rand::{thread_rng, Rng};

fn main() {
    let mut rng = thread_rng();
    let rand_number: u32 = rng.gen_range(0, 11);
    println!("Random number: {}", rand_number);

    let rand_bool: bool = rng.gen_bool(1.0/3.0);
    println!("Random boolean: {:?}", rand_bool);
}

###Rust examples_024

fn main() {
    {
        /* replace */
        let my_string = String::from("Rust is fantastic!");
        println!(
            "After replace is: {}",
            my_string.replace("fantastic", "great")
        );
    }

    {
        /* lines */
        let my_string = String::from("The weather is\nnice\noutside mate!");
        for line in my_string.lines() {
            println!("[ {} ]", line);
        }
    }

    {
        /* split */
        let my_string = String::from("leave+a+like+if+you+enjoy!");
        let tokens: Vec<&str> = my_string.split("+").collect();
        println!("At index 2: {}", tokens[2]);
    }

    {
        /* trim */
        let my_string = String::from("      my name is dom    \r\n");
        println!("Before trimming is: {}", my_string);
        println!("After trimming is : {}", my_string.trim());
        println!("改行もトリミングされました。");
    }

    {
        /* chars */
        let my_string = String::from("decode on YouTube");
        println!("My string is: {}", my_string);
        match my_string.chars().nth(4) {
            Some(c) => println!("Character at index 4: {}", c),
            None => println!("No Character at index 4.")
        }
    }
}

###Rust examples_025

  • 別ファイル(dcode.rs)にfnを定義する
pub fn print_message() {
    println!("How's it going? My name is Dom!");
}
  • main.rsに「mod」でimportする
mod dcode;
fn main() {
    dcode::print_message();
}

###Rust examples_026

[dependencies]
regex = "*"
extern crate regex;
use regex::Regex;

fn main() {
    let re = Regex::new(r"(\w{5})").unwrap();
    let text = "dcode";

    println!("Found match?{}",re.is_match(text));

    match re.captures(text){
        Some(caps) => println!("Found match: {:?}",caps.get(0).unwrap().as_str()),
        None => println!("Could not found match...")
    }
}

###Rust examples_027

mod dcode {
    fn chicken() {
        println!("Chicken!");
    }

    pub fn print_message() {
        chicken();
        println!("How is it going?");
    }

    pub mod water {
        pub fn print_message(){
            println!("I'm water!");
        }
    }
}

fn main() {
    dcode::print_message();
    dcode::water::print_message();
}

###Rust examples_028

fn main() {
    let name = String::from("Dominic");
    println!(
        "Occupation is {}",
        match get_occupation(&name) {
            Some(o) => o,
            None => "No occupation found!",
        }
    );
}

fn get_occupation(name: &str) -> Option<&str> {
    match name {
        "Dominic" => Some("Software Developer"),
        "Michel" => Some("Dentist"),
        _ => None,
    }
}

###Rust examples_029

#[allow(dead_code)]
enum Day {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday,
}

impl Day {
    fn is_weekday(&self) -> bool {
        match self {
            Day::Saturday | Day::Sunday => return false,
            _ => return true,
        }
    }
}
fn main() {
    let d = Day::Tuesday;
    println!("Is d a weekday? {}", d.is_weekday());
    let d = Day::Saturday;
    println!("Is d a weekday? {}", d.is_weekday());

}

###Rust examples_030

fn main() {
    let v = vec![12, 34, 5, 6, 6, 7, 7, 7, 56, 5, 54, 5, 4, 5];

    for &i in &v {
        let r = count(&v, i);
        println!("{} is repeated {} times.", i, r);
    }
}

fn count(v: &Vec<i32>, val: i32) -> usize {
    v.into_iter().filter(|&&x| x == val).count()
}
  • 実行結果
    borrow.png
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?