You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中如何返回类字段指针以避免拷贝并允许外部修改?

Rust返回结构体中Vec字段指针的正确写法

原代码的核心错误

  1. 裸指针类型语法错误:你写的*Vec<point::Point>::const不符合Rust语法,正确的不可变/可变裸指针类型应为*const Vec<point::Point>或*mut Vec<point::Point>。
  2. 引用无法直接转为裸指针:&self.packets是引用类型,必须通过as关键字显式转换为裸指针。

满足需求的正确实现

如果你确实需要返回裸指针以允许外部修改,可以这样写:

pub fn get_packets(&mut self) -> *mut Vec<point::Point> {
    // 将可变引用显式转为可变裸指针
    &mut self.packets as *mut Vec<point::Point>
}

如果只需要读取不需要修改,用不可变裸指针:

pub fn get_packets(&self) -> *const Vec<point::Point> {
    &self.packets as *const Vec<point::Point>
}

更推荐的安全替代方案

在Rust中,优先使用可变引用实现“避免拷贝+允许外部修改”的需求,这符合Rust的内存安全规则,不需要使用裸指针:

pub fn get_packets(&mut self) -> &mut Vec<point::Point> {
    &mut self.packets
}

调用时可以直接修改vector:

obj.get_packets().push(point::Point { x: 0, y: 0 });

内容的提问来源于stack exchange,提问作者pdaranda661

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 19:09:27