简体   繁体   中英

Execute a statement while debugging in Rust

While Coding in Python, I often do something like

test.py

x = []
breakpoint()
± |master U:5 ?:4 ✗| → python3 test.py 
-> breakpoint()
(Pdb) x
[]
(Pdb) x.append(1)
(Pdb) x
[1]

Is it possible to execute the statement while debugging Rust?

use std::collections::HashMap;

fn main() { 
    let mut contacts = HashMap::new();

    contacts.insert("Daniel", "798-1364");
    contacts.insert("Ashley", "645-7689");
    //set breakpoint here
}

So far, I can execute p contacts in the debug console, the meaning of this output isn't straight to me. What if I want to know the outcome of println!("{:?}", contacts); without writting this line of code in the source file.

And also I want to know the outcome of contacts.insert("Robert", "956-1742") , If I execute expr contacts.insert("Robert", "956-1742") in the debug console, it says error: no field named insert .

Rust debugging support is currently quite limited with both lldb and gdb. Simple expressions work, anything more complex is likely to cause problems.

My experience while testing this with rust-lldb :

  • The expression parser only understands a limited subset of Rust. Macros are not supported.
  • Functions that are not used are not included in the resulting binary. Eg you cannot call capacity() on the HashMap in the debugger since that function is not included in the binary.
  • Methods have to be called like this: struct_value.method(&struct_value)
  • I haven't found a way to call monomorphized methods on generic structs (like HashMap ).
  • String constants "..." in lldb expressions are created as C-style string constants, eg "abcdef" is a const char [7] including the trailing NUL byte. Thus they cannot be easily passed to Rust functions expecting &str arguments.

Trying to use a helper function like this:

pub fn print_contacts(contacts: &HashMap<&str, &str>) {
    println!("{:?}", contacts);
}

causes lldb to crash:

(lldb) expr print_contacts(&contacts)
PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash backtrace.
Stack dump:
0.  Program arguments: [...]
Segmentation fault: 11

So it seems that what you want to do is not possible at this time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM