如何在Rust中返回可变全局字符串的引用?
Rust正则表达式搜索程序的全局缓冲引用问题
背景
- 正在开发Rust正则表达式搜索程序,已实现基础功能,需新增从文件或标准输入读取待搜索字符串的功能,不提前读取全部输入,而是分批向全局缓冲字符串追加内容。
- 程序为单线程无事件模型,无并发协调问题。
- 不想将
Input结构体逐层传递给子函数,原因有二:- 需重写整个模块以支持此前不需要的错误返回,工作量大;
- 最终报告、追踪调试时,对象需引用该字符串,无法在
Debugtrait中传递它。
当前代码结构
enum Source { CmdLine, Stdin(BufReader<std::io::Stdin>), File(BufReader<std::fs::File>) } impl Source { /// Extends fn extend(&mut self) -> std::io::Result<String> { let mut string = "".to_string(); match self { Source::CmdLine => (), Source::File(stream) => while stream.read_line(&mut string)? > 0 && string.len() < Input::BLOCK_SIZE {}, Source::Stdin(stream) => while stream.read_line(&mut string)? > 0 && string.len() < Input::BLOCK_SIZE {}, } Ok(string) } } /// Buffers the string to search. Unwanted characters can be removed from the front and new ones can be added to the end. pub struct Input { /// The text currently in the buffer pub full_text: String, /// The source for getting more text source: Source, /// the byte offset of the front of the buffer (number of bytes deleted) b_start: usize, /// the character offset of the front of the buffer (number of characters deleted) c_start: usize, /// start of the current search in the buffered text, in bytes b_offset: usize, /// start of the current search in the buffered text, in chars c_offset: usize } thread_local!(static INPUT: RefCell<Input> = RefCell::new(Input::from_stdin().unwrap()));
核心问题
希望从函数返回全局Input结构体中full_text的切片。清楚字符串扩展时引用会失效,但实际使用场景不会出现该问题:
- 遍历阶段:字符串可能增长,但切片会被立即使用(匹配对比或打印追踪)后就超出作用域;
- 报告阶段:字符串不再增长,地址固定(可按需获取切片,无需长期持有)。
编译时出现生命周期错误,无法返回RefCell::borrow()的引用。
已知变通方案
- 将
Input结构体逐层传递到各处; - 向
Input实例传入闭包执行测试; - 自定义调试逻辑替代
println!; - 返回字符串副本而非切片;
- 返回
String使用后再归还。
提问
- 有没有不使用
unsafe{}的最佳实践? - 这种场景是否可以使用
unsafe{}? - 还是只能通过重构将
Input结构体传递到各处?
内容的提问来源于stack exchange,提问作者russell
相关产品推荐
相关产品推荐

