深入浅出Rust:函数、控制流与所有权核心特性解析Rust作为一门现代系统编程语言,以其内存安全、高性能和并发能力而备受推崇。本文深入探讨Rust的核心概念,包括函数的定义与使用、控制流的灵活运用,以及所有权机制的独特设计。通过代码示例和详细解析,带你快速掌握Rust的精髓,无论是初学
Rust 作为一门现代系统编程语言,以其内存安全、高性能和并发能力而备受推崇。本文深入探讨 Rust 的核心概念,包括函数的定义与使用、控制流的灵活运用,以及所有权机制的独特设计。通过代码示例和详细解析,带你快速掌握 Rust 的精髓,无论是初学者还是有经验的开发者,都能从中受益。
本文全面介绍了 Rust 编程语言的三大核心主题:函数、控制流和所有权。函数部分涵盖了函数声明、参数传递、表达式与语句的区别,以及返回值处理;控制流部分探讨了 if 表达式、match 模式匹配,以及 loop、while、for 三种循环的用法;所有权部分深入剖析了 Rust 独特的内存管理机制,包括栈与堆的区别、所有权规则、引用与借用、切片等概念。通过清晰的代码示例和解释,本文帮助读者理解 Rust 的设计哲学及其在系统编程中的优势。
fn main() {
another_function();
}
fn another_function() {
println!("Another function");
}
fn main() {
another_function(5, 6); // argument
}
fn another_function(x: i32, y: i32) { // parameter
println!("the value of x is {}", x);
println!("the value of y is {}", y);
}
fn main() {
let y = 6; // 语句
// let x = (let y = 6); // 报错
let x = 5;
let y = {
let x = 1;
x + 3
};
println!("The value of y is {}", y)
}
fn plus_five(x: i32) -> i32 {
x + 5
}
fn main() {
let x = plus_five(6);
println!("The value of x is {}", x);
}
// This is a function
fn five(x: i32) -> i32 {
x + 5
}
/* sdgagaf
sfgagaga */
// This is main function
// The entry point
fn main() {
// call five()
let x = five(6); // 5 + 6
println!("The value of x is: {}", x);
}
fn main() {
println!("Hello, world!");
let number = 7;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
fn main() {
let number = 6;
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");
}
}
使用match
fn main() {
let number = 6;
match number {
number if number % 4 == 0 => println!("number is divisible by 4"),
number if number % 3 == 0 => println!("number is divisible by 3"),
number if number % 2 == 0 => println!("number is divisible by 2"),
_ => println!("number is not divisible by 4, 3 or 2"),
}
}
fn main() {
let condition = true;
let number = if condition {5} else {6};
println!("The value of number is {}", number);
}
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {}", result);
}
fn main() {
let mut number = 3;
while number != 0 {
println!("{}", number);
number = number - 1;
}
println!("LIFTOFF!!!");
}
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the index is {}", a[index]);
index = index + 1;
}
}
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is {}", element);
}
}
fn main() {
for number in (1..4).rev() {
println!("{}", number);
}
println!("LIFTOFF!!!");
}
栈内存 VS 堆内存
存储数据
访问数据
函数调用
所有权存在的原因
fn main() {
// s 不可用
let s = "hello"; // s 可用
// 可以对 s 进行相关操作
} // s 作用域到此结束,s 不再可用
fn main() {
let mut s = String::from("Hello");
s.push_str(", World");
println!("{}", s);
}
String::from
来实现let x = 5;
let y = x;
String版本
let s1 = String::from("hello");
let s2 = s1;
fn main() {
let s1 = String::from("Hello");
let s2 = s1.clone();
println!("{}, {}", s1, s2);
}
fn main() {
let x = 5;
let y = x;
println!("{}, {}", x, y);
}
(i32, i32)
是(i32, String)
不是fn main() {
let s = String::from("Hello, World!");
take_ownership(s);
let x = 5;
makes_copy(x);
println!("x: {}", x);
}
fn take_ownership(some_string: String) {
println!("{}", some_string)
}
fn makes_copy(some_number: i32) {
println!("{}", some_number);
}
fn main() {
let s1 = gives_ownership();
let s2 = String::from("hello");
let s3 = takes_and_gives_back(s2);
}
fn gives_ownership() -> String {
let some_string = String::from("hello");
some_string
}
fn takes_and_gives_back(a_string: String) -> String {
a_string
}
fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("The length of '{}' is {}.", s2, len);
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len();
(s, length)
}
fn main() {
let s1 = String::from("Hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
fn main() {
let mut s = String::from("Hello");
{
let s1 = &mut s;
}
let s2 = &mut s;
}
fn main() {
let mut s = String::from("Hello");
let r1 = &s;
let r2 = &s;
let s1 = &mut s; // 报错
println!("{} {} {}", r1, r2, s1);
}
fn main() {
let mut s = String::from("Hello world");
let word_index = first_world(&s);
println!("{}", word_index);
}
fn first_world(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
fn main() {
let s = String::from("Hello world");
let hello = &s[0..5];
let world = &s[6..11];
println!("{}, {}", hello, world);
}
fn main() {
let s = String::from("Hello world");
let word_index = first_world(&s);
println!("{}", word_index);
}
fn first_world(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[..i];
}
}
&s[..]
}
fn main() {
let s = "Hello world";
println!("{}", s)
}
fn first_word(s: &String) -> &str {
fn first_word(s: &str) -> &str {
fn main() {
let my_string = String::from("Hello world");
let word_index = first_world(&my_string[..]);
println!("{}", word_index);
let my_string_literal = "hello world";
let word_literal = first_world(my_string_literal);
println!("word_literal: {}", word_literal);
}
fn first_world(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[..i];
}
}
&s[..]
}
fn main() {
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
}
Rust 的函数、控制流和所有权机制共同构成了其高效、安全的核心优势。函数通过基于表达式的设计提供了灵活性和简洁性;控制流结构如 if、match 和多样化的循环方式,使得代码逻辑清晰且高效;所有权机制通过编译时检查和引用借用规则,消除了内存管理中的常见错误,为开发者提供了无垃圾回收器的高性能内存安全保障。掌握这些特性,不仅能帮助开发者编写健壮的 Rust 代码,还能深入理解系统编程的底层原理。无论是构建高性能系统还是探索现代编程语言的设计,Rust 都是一个值得深入学习的强大工具。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!