備忘録

備忘録

Rust 基本文法メモ

fn say_hello(name: String) {
  println!("hello {name} !!!");
}

fn sum(a: i32, b: i32) -> i32 {
  return a + b;
}

fn main() {
  println!("Hello, world!");
  println!("aaa {}", "bbb");

  let mut a: i32 = 1;
  println!("a is :{}", a);
  a = 2;
  println!("a is :{}", a);

  let a: &str = "aaa";

  let a1: i32 = 1;
  let a2: u32 = 1;
  let a3: f64 = 1.0;
  let a4: bool = true;

  // cast
  let floatValue = 1 as f64;

  // tuple
  let tuple1 = (1,true, 2.0);
  let tuple2 = (1,true, 2.0);

  println!("{:?}", tuple1); // 全ての値
  println!("{:?}", tuple1.0); // インデックスで要素を指定する
  println!("{}", tuple1 == tuple2); // 比較

  // array
  let array1: [i32; 3] = [1,2,3]; // 1,2,3
  let array2: [i32; 100] = [0; 100]; // 0, 0, 0, .... 0

  println!("{:?}", array1);
  println!("{}", array1[0]);

  // Vector
  let vector1: Vec<i32> = vec![1,2,3];// 1,2,3
  let vector2: Vec<i32> = vec![0; 100]; // 0, 0, 0, .... 0
  let mut vector3 :Vec<i32> = Vec::new();
  vector3.push(1);
  vector3.push(2);
  vector3.push(3);
  println!("{vector3:?}");

  // LINQ
  // https://microsoft.github.io/rust-for-dotnet-devs/latest/linq/index.html
  let results = array1
      .iter()
      .filter(|x| x >= &&2)
      .collect::<Vec<&i32>>();

  println!("{results:?}");

  // char
  let c1: char = 'a';
  let c2: char = '😂';
  println!("{c1}, {c2}");

  // String
  let string1: String = String::from("abc");
  let mut string2: String = "def".to_string();
  string2 = string2 + " ghi";

  println!("{string2}");

  let string3 = format!("{string1}{string2}!!!");
  println!("{string3}");

  // Function
  say_hello("tanaka".to_string());
  println!("{}", sum(1, 2));

  // if
  if 1 > 0 && (true || false) {
      println!("aaa");
  } else if 1 > 0 {
      println!("bbb");
  } else {
      println!("ccc");
  }

  let result = if true { true } else {false};
  println!("{}", result);

  // Switch
  let x: i32 = 3;
  match x {
      0 => println!("x is 0"),
      1 | 2 => {
      println!("x is 1 or 2");
      println!("Multi line");
      },
      _ => println!("x is unknown")
  }

  let result = match x { 0 => 0, 1=>1, _=> 999};
  println!("{}", result);

  // While true
  let mut x: i32 = 0;
  loop {
      x += 1;
      if x > 10 {
      break;
      }

      if x %2 == 0 {
      continue;
      }

      println!("hello");
  }

  // while
  let mut x: i32 = 0;
  while x < 10 {
      println!("while x: {}", x);
      x += 1;
  }

  // for
  for x in [1,2,3] {
      println!("for x: {}", x);
  }
}
// 関数引数の参照渡し
fn concat (a: &String, b: &String) -> String{
  return format!("{a}{b}");
}

fn main(){
  let s1: String = "hello".to_string();
  let s2: String = "world".to_string();
  let s3: String = concat(&s1, &s2);

  println!("{s1} {s2} {s3}");
}