下面簡單的用unsafe Rust完成一個三節(jié)點鏈表(主要原因是safe Rust的所有權(quán)讓我頭大)
連接,遍歷的思想與C語言里的完全相同.
struct Linknode {
data: i32,
ptr: *const Linknode,
}
impl Linknode {
fn new(input: i32) -> Linknode {
Linknode {
data: input,
ptr: std::ptr::null(),
}
}
}
fn main() {
let mut node1 = Linknode::new(1);
let mut node2 = Linknode::new(2);
let node3 = Linknode::new(3);
//連接
node1.ptr = &node2 as *const Linknode;
node2.ptr = &node3 as *const Linknode;
//遍歷
println!("---------------------");
let mut p = &node1 as *const Linknode;
unsafe{
//當(dāng)解引用裸指針時需要用unsafe代碼塊
while !p.is_null()
//沒到鏈表結(jié)尾時
{
print!("{}->",(*p).data);
p = (*p).ptr;
}
}
//插入
println!("");
let mut new_node = Linknode::new(666);//插入新節(jié)點 data域為666
new_node.ptr = &node3 as *const Linknode;
node2.ptr = &new_node as *const Linknode;
p = &node1 as *const Linknode;
unsafe{
//展示
while !p.is_null()
{
print!("{}->",(*p).data);
p = (*p).ptr;
}
}
//刪除
println!("");
node2.ptr = &node3 as *const Linknode;
drop(new_node);//清理掉新的節(jié)點
p = &node1 as *const Linknode;
unsafe{
//展示
while !p.is_null()
{
print!("{}->",(*p).data);
p = (*p).ptr;
}
}
}
運行結(jié)果如下圖所示:

運行結(jié)果
需要注意的是我這里使用的裸指針類型為*const T,即裸指針指向的內(nèi)容不可變,若想讓data域可變應(yīng)該使用*mut T 類型

兩種裸指針,見Rust標(biāo)準(zhǔn)庫