Rust 函数/条件语句


1.表达式块

fn main() {
 let s = 4;
 let s = add(s,2);
 let e = {            //表达式块
   let tmp = 4;
   tmp*2
 };
 println!("The value of s is {0},e is {1}",s,e);
}


///Add num1 to num2
/// 
/// sample:let a = add(1,1);
/// 
fn add(a:i32,b:i32) -> i32
{
    return a+b;
}
结果:
The value of s is 6,e is 8
2.函数体表达式
fn main() {
    fn equal(a:i32,b:i32)->bool{       //函数体表达式
        if a-b==0
        {
            true
        }
        else
        {
            false
        }
    }
    
    println!("two number is equal:{}",equal(2,3));
    
    }

运行结果:

3.for循环

a.迭代器

fn main() {
    let a = [10, 20, 30, 40, 50];
    for i in a.iter() {
        println!("值为 : {}", i);
    }
}

运行结果:

 b.通过下标访问数组:

  

fn main() {
let a = [10, 20, 30, 40, 50];
    for i in 0..5 {
        println!("a[{}] = {}", i, a[i]);
    }
}

运行结果:

 

 4.无限循环结构-loop

fn main() {
    let a = ['E','C','H','O','E','F','U','N'];
    let mut i =0;
    let mut e_count = 0;
    let counts = loop{
        let tmp = a[i];
        
        if tmp=='E'{
            e_count+=1;
        }
        i+=1;
        if i >= a.len()
        {
            break i;
        }
    };
    
    println!("{} Chars have char E num is {}",counts,e_count);
}

 运行结果: