Rust的函数参数默认是通过移动语义按值传递。将一个变量传递给函数时,这个变量的所有权会被移动到函数的参数上。

fn hello() {
	println!("Hello World!")
}
// 带返回值的函数,最后一行为返回值,不带分号
// -> 后声明返回值类型
fn add_five(x: i32) -> i32 { 
	x + 5 
}

函数在声明时必须指定参数的类型。

参数类型可以是引用或。

fn main() {
    let s1 = String::from("hello");
 
    let len = calculate_length(&s1);
 
    println!("The length of '{s1}' is {len}.");
}
 
fn calculate_length(s: &String) -> usize {
    s.len()
}

Three tables: the table for s contains only a pointer to the table for s1. The table for s1 contains the stack data for s1 and points to the string data on the heap.