admin管理员组文章数量:1364817
I’m porting a C data structure to Rust where a struct holds a pointer to a field of another struct. Here’s the C code:
struct Node { struct Node *next; };
struct Tree {
struct Node *start;
struct Node **dangling_arrow; // Points to a Node's 'next' field
};
int main() {
struct Node node;
struct Tree tree;
tree.dangling_arrow = &node.next; // Modify later via *dangling_arrow
}
In Rust, I need dangling_arrow
to point to a heap-allocated Node's next field. Multiple Tree
instances may reference this field. My attempt:
struct Node {
next: Option<Box<Node>>,
}
struct Tree {
start: Option<Box<Node>>,
dangling_arrow: *mut Option<Box<Node>>, // Raw pointer to Node's 'next'
}
fn main() {
let mut node = Box::new(Node { next: None });
let mut tree = Tree {
start: Some(node),
dangling_arrow: &mut node.next as *mut _,
};
}
This compiles but may have undefined behavior since node is moved into tree.start
, invalidating dangling_arrow
. How can I safely manage this pointer, preferably with minimal overhead?
I’ve tried Rc<RefCell<Node>>
but it adds runtime checks. Is there an unsafe approach that ensures lifetime validity?
本文标签: Storing raw pointers to struct fields in RustStack Overflow
版权声明:本文标题:Storing raw pointers to struct fields in Rust - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743803226a2541703.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论