我对Rust中指针的工作方式感到有些困惑.有ref,Box,&,*,我不知道他们是如何协同工作.
这是我目前的理解方式:
Box 它实际上不是一个指针 - 它是一种在堆上分配数据的方法,并在函数参数中传递未经过类型化的特性(特别是特征).ref用于模式匹配以借用你匹配的东西,而不是拿它.例如,
let thing: Option<i32> = Some(4);
match thing {
None => println!("none!"),
Some(ref x) => println!("{}", x), // x is a borrowed thing
}
println!("{}", x + 1); // wouldn't work without the ref since the block would have taken ownership of the data
Run Code Online (Sandbox Code Playgroud)&用来借(借来的指针).如果我有一个函数,fn foo(&self)那么我正在引用自己的函数将在函数终止后过期,只留下调用者的数据.我也可以传递我想要保留所有权的数据bar(&mydata).
*用于制作原始指针:例如,let y: i32 = 4; let x = &y as *const i32 …