rust入门(2)

一、变量的可变性   

  最基本的赋值   :    let   mut   变量名称:变量类型 =  变量值 ;

  a>   let x=5;x=6;   (×)     let mut x=5; x=6;(√) 

  b>  const   常量赋值 ;   const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;//跟 c# 中的用法一样;

  c>  Shadowing  变量覆盖;同一作用域下, let 同一个变量名称,前面的会被覆盖。

fn main() {
    let x = 5;
    let x = x + 1;
    {
        let x = x * 2;
        println!("The value of x in the inner scope is: {x}");
    }
    println!("The value of x is: {x}");
}

二、基本数据类型  

  a>数值类型       整数类型 和其他语言差不多,i表示有符号,u表示无符号;  i/u  后边的数字表示位数,例如  i8,u32 等等;

  b>浮点类型  浮点类型就两种 f32 和 f64,一般和 电脑的cpu一样;   数字的计算符号  + - * / %

  c>布尔类型  let t = true;    let f: bool = false; // with explicit type annotation

  d>字符类型  let c = 'z';   let z: char = 'ℤ'; // with explicit type annotation    let heart_eyed_cat = '😻';

  e>复合类型  

    1>Tuple  let tup: (i32, f64, u8) = (500, 6.4, "你好");   可以这样取值  tup.0; 括号里面的数据类型可以不一致;

    2>Array  元素类型一致,长度固定;

          let a = [1, 2, 3, 4, 5]; 

            let a: [i32; 5] = [1, 2, 3, 4, 5];     

            let a = [3; 5];    equal  let a = [3, 3, 3, 3, 3];   

三、函数

  fn 函数名称(参数名称:参数类型,。。。。)->返回值类型{  }

  可以没有参数,小括号为空;可以没有返回值,去掉  (->返回值类型)

  如果函数有返回值,可以用 return value 返回;也可以Rust 默认的方式   即 {。。。。}  中的最后一行是返回值且不要加结束符号”:“;

四、代码注释

  // 就好啦

五、循环、遍历

  loop  while  for; for用的最多; break 打破循环; continue 继续下一个循环; 

  for number in 数组 {}

  for number in 1..4 {}// 中间两个点   表示一个rang;

 

posted @ 2022-08-11 17:53  丢丢乱射  阅读(52)  评论(0编辑  收藏  举报