Skip to content

函数,控制流,slice类型

函数

fn关键字,声明新函数,Rust 代码中的函数和变量名使用 snake case 规范风格。在 snake case 中,所有字母都是小写并使用下划线分隔单词

rust
fn main() {
    println!("Hello, world!");
    another_function();
    //参数
    another_function2(5);
    print_labeled_measurement(5, 'h');
}
fn another_function() {
    println!("Another function.");
}
fn another_function2(x: i32) {
    println!("The value of x is: {x}");
}
fn print_labeled_measurement(value: i32, unit_label: char) {
    println!("The measurement is: {value}{unit_label}");
}
//具有返回值的函数(不加分号)
fn five() -> i32 {
    5
}

语句和表达式

语句是执行一些操作但不返回值的指令,表达式计算并产生一个值;

rust
fn main() {
    let y = 6;//语句
    //表达式
    {
    	let x = 3;
    	x + 1
	}//计算的结果是4 将4赋值给y	
     let y = {
        let x = 3;
        x + 1
    };
}

控制流

if表达式

rust
fn main() {
    let number = 3;
    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }
    
     if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }
    //let语句中使用if
    let condition = true;
    let number2 = if condition { 5 } else { 6 };

    println!("The value of number2 is: {number2}");
}
}

循环

rust
fn main() {
    let mut counter = 0;
	//loop循环;
    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;//跳出循环
        }
    };

    println!("The result is {result}");
}
//循环标签
fn main() {
    let mut count = 0;
    'counting_up: loop {
        println!("count = {count}");
        let mut remaining = 10;

        loop {
            println!("remaining = {remaining}");
            if remaining == 9 {
                break;
            }
            if count == 2 {
                break 'counting_up;//跳出counting_up循环
            }
            remaining -= 1;
        }

        count += 1;
    }
    println!("End count = {count}");
}
//while循环
fn main() {
    let mut number = 3;
    while number != 0 {
        println!("{number}!");
        number -= 1;
    }
    println!("LIFTOFF!!!");
    //读取数组
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;
    while index < 5 {
        println!("the value is: {}", a[index]);
        index += 1;
    }
}
//for循环
fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a {
        println!("the value is: {element}");
    }
}

slice 类型

slice 允许你引用集合中一段连续的元素序列,而不用引用整个集合。slice 是一种引用,所以它没有所有权。

字符串slice

如果尝试从一个多字节字符的中间位置创建字符串 slice,则程序将会因错误而退出。

rust
    let s = String::from("hello world");

    let hello = &s[0..5];
    let world = &s[6..11];

	//对于 Rust 的 .. range 语法,如果想要从索引 0 开始,可以不写两个点号之前的值
	//他俩语句是相同的
	let slice = &s[0..2];
	let slice = &s[..2];
	//如果 slice 包含 String 的最后一个字节,也可以舍弃尾部的数字
	//他俩语句是相同的
	let slice = &s[3..len];
	let slice = &s[3..];
rust
fn main() {
    let s = String::from("hello world");
    let word = first_word(&s);//hello
}

fn first_word(s: &String) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            // b' ' 表示空格字符的字节表示
            println!("the item is: {}", i);
            return &s[0..i];
        }
    }
    &s[..]
}

fn main() {
    let my_string = String::from("hello world");
    // `first_word` 适用于 `String`(的 slice),部分或全部
    let word = first_word(&my_string[0..6]);
    let word = first_word(&my_string[..]);
    // `first_word` 也适用于 `String` 的引用,
    // 这等价于整个 `String` 的 slice
    let word = first_word(&my_string);

    let my_string_literal = "hello world";

    // `first_word` 适用于字符串字面值,部分或全部
    let word = first_word(&my_string_literal[0..6]);
    let word = first_word(&my_string_literal[..]);

    // 因为字符串字面值已经 **是** 字符串 slice 了,
    // 这也是适用的,无需 slice 语法!
    let word = first_word(my_string_literal);
}
fn first_word(s: &str) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            // b' ' 表示空格字符的字节表示
            println!("the item is: {}", i);
            return &s[0..i];
        }
    }
    &s[..]
}

其他类型的slice

rust
//数组
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
assert_eq!(slice, &[2, 3]);
print!("slice:{:?}", slice);