惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Jina AI
Jina AI
小众软件
小众软件
GbyAI
GbyAI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
D
DataBreaches.Net
腾讯CDC
V
Visual Studio Blog
博客园 - 叶小钗
B
Blog
Apple Machine Learning Research
Apple Machine Learning Research
T
The Blog of Author Tim Ferriss
S
SegmentFault 最新的问题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
博客园 - 三生石上(FineUI控件)
云风的 BLOG
云风的 BLOG
The Cloudflare Blog
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
U
Unit 42
博客园 - 司徒正美
博客园 - 聂微东

The Rust Programming Language Forum - Latest posts

What's everyone working on this week (21/2026)? Rust Function Call with one Param Iced + Canvas + Text: How do I create a style for canvas text "Value dropped while borrowed" as a lifetime mismatch Weird `use of moved value` behaviour Slightly surprising behavior of a while loop Clap: how to disable options after a certain positional argument How do i tell rust-analyzer what kind of bracket to use for a macro? Iterator + Borrow Checker: Work around borrowing already borrowed mutable variable Requesting data via mavlink SKILLS.md for Rust development 🧵 Stringlet UTF-8 Hack Option Niche? Iterator + Map - How do divide every element, including the last element, by the last element Why can't we store returned value of a function in a variable if one of the parameters goes out of scope My first crate :D, floop: A more convenient and less error prone replacement for loop `{ select! { .. }}` Sorting is slow because architectures are wrong — zan-sort redesigns the architecture, not the algorithm Iced Font - Create a custom monospace font to display dollar amounts Is the UnsafePinned RFC wrong about being able to return `&mut T` from `get_mut_unchecked`? Fixing Polars 0.37 compilation errors: Hashbrown 0.17 dependency conflict and decimal parsing Any plans for improving error diagnostic in Rust 2.0? How do I build completely offline? Is `&mut T -> &mut ManuallyDrop<T>` well-defined and sound? Would you use this? — fixtura, declarative fake data injection for tests Foreign trait restrictions on native types make generics hard to use Cargo Exclude Directive Compiler reasoning around a modulo counter Multiple mutable references to elements within one vector Handling non-`Send` data in a `Send` closure Review: Static Multi Pool Allocator Rmquickjs - High-level MicroQuickJS bindings for Rust
How to call struct method as function pointer in loop
magast · 2026-04-20 · via The Rust Programming Language Forum - Latest posts

1

I write a parser to analyze the text. I want to store the methods into a HashMap, like the table-driven approach in C languange, to reduce the match-select code. then I can call the method by accessing the HashMap using the state as key. But there are a few tricky problems.
My intention is to use a concise method to replace numerous branches(match-select, if-else and so on).
NOTE: It needs to support the lifetime if feasible.

The sample code as following:

use std::collections::HashMap;

//It needs to set lifetime to match the Parser<'a>
type HandlerPtr<'a> = fn(&'a mut Parser<'a>)->i32;

//It need lifetime to support the buffer reference
pub struct Parser<'a> {
    //It MUST be the reference here
    buffer: &'a [u8],
    state: i32,
    handlers: HashMap<i32, HandlerPtr<'a>>,
}

impl<'a> Parser<'a> {
    pub fn new(buf: &'a [u8]) -> Self {
        Self{
            buffer: buf,
            state: -1,
            handlers: HashMap::new(),
        }
    }

    pub fn init(&mut self) {
        self.handlers.insert(-1, Parser::handle_none);
        self.handlers.insert(0, Parser::handle_one);

    }

    pub fn test(&'a mut self) {
        let mut state = -1_i32;
        //Compiling error when accessing the HashMap more than once
        for _i in 0..3{
            let myfn = self.handlers.get(&state).unwrap();
            state = myfn(self);
            println!("---test: {}", state);
        }
    }

    pub fn handle_none(&'a mut self) -> i32 {
        let ch = self.buffer[0];
        println!("[handle_none] {:?}", ch);
        //change state

        self.state = 0;
        self.state
    }

    pub fn handle_one(&mut self) -> i32 {
        let ch = self.buffer[1];
        println!("[handle_one] {:?}", ch);

        self.state = -1;
        self.state
    }
}

fn main() {
    let buf = [0_u8;16];
    let mut p = Parser::new(&buf);
    p.init();
    p.test();
}

The compiler report the error as:

let myfn = self.handlers.get(&state).unwrap();
   |                        ------------------------- argument requires that `*self` is borrowed for `'a`
   |             state = myfn(self);
   |                          ^^^^ `*self` was mutably borrowed here in the previous iteration of the loop

There are more then once mutable borrowed if I want to access the method function pointer. I try the version without lifetime, it works. But it seems unsolvable in the lifetime version.
Does anyone know how to fix the issues? Or can give other alternative solutions?
Thank you!

2

Change all the &'a mut to &mut to get it to compile.
(Whether you should be trying to write code how you have it could be debatable, but not much to go on.)