发布于2026-07-10 阅读(0)
扫一扫,手机访问
Let’s talk about debugging Rust code on Ubuntu. Whether you’re hunting down a logic error or tracking a memory issue, the right setup makes all the difference. Here’s a practical walkthrough—from basic print statements to full IDE integration.

First things first: make sure your Rust program carries debug symbols. The default cargo build already includes them, but if you need finer control—say, to adjust the verbosity of debug logs—you can tune the debug profile inside Cargo.toml.
cargo build
# Debug build (includes debug info)
[profile.dev]
debug = true # Enabled by default
println!/dbg!: For quick checks, println!("{:?}", variable) prints values, while dbg!(variable) goes a step further—it shows the file, line number, and the value in one handy output. Example:fn main() {
let x = 42;
dbg!(x); // Output: [src/main.rs:2] x = 42
}sudo apt install gdb lldbcargo build.gdb target/debug/your_program.break main.rs:5), run (run), step through (next/step), inspect variables (print x).lldb target/debug/your_program.breakpoint set --name main, run, next, and frame variable.Rust ships clever wrappers around GDB and LLDB. They automatically load debug symbols and improve the display of Rust-specific types (enums, structs, etc.). Fire them up the same way:
rust-gdb target/debug/your_program # Rust-aware GDB
rust-lldb target/debug/your_program # Rust-aware LLDB
If you prefer a graphical interface, VS Code with the rust-analyzer extension is a solid choice. Here’s how to set it up:
rust-analyzer from the VS Code marketplace.launch.json in .vscode/ with a debug configuration like this:{
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug",
"program": "${workspaceFolder}/target/debug/your_program",
"args": [],
"cwd": "${workspaceFolder}"
}
]
}F5, and use the debug sidebar to inspect variables, call stacks, and control execution.Structured logging with the log crate and env_logger gives you runtime control over verbosity. Add the dependencies to Cargo.toml:
[dependencies]
log = "0.4"
env_logger = "0.10"
Then initialize the logger in main.rs:
use log::{info, warn};
fn main() {
env_logger::init(); // Initialize logger
info!("Program started");
warn!("This is a warning");
}
Control log levels at runtime via environment variables:
RUST_LOG=info cargo run # Show INFO and higher logs
Now let's flip the coin and talk about optimizing Rust code on Ubuntu—because debugging is only half the story.
release Mode: The --release flag turns on inlining, loop unrolling, and other goodies. For production builds, there’s no going around it:cargo build --releaseRUSTFLAGS. Enabling link-time optimization (LTO) often squeezes out extra performance:RUSTFLAGS="-C opt-level=3 -C lto" cargo build --releaseVec::with_capacity(100) to reduce dynamic resizing overhead.iter().sum() is both cleaner and more efficient.let sum: i32 = vec![1, 2, 3].iter().sum();Mutex locks minimal, and consider tokio::sync::Mutex for async code to a void bottlenecks.rayon crate, parallelizing a sum is almost trivial:use rayon::prelude::*;
let sum: i32 = vec![1, 2, 3].par_iter().sum();tokio handles concurrent connections without breaking a sweat. Here’s a minimal echo server:use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> Result<(), Box> {
let listener = TcpListener::bind("127.0.0.1:8080").await?;
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0; 1024];
loop {
let bytes_read = socket.read(&mut buf).await.unwrap();
if bytes_read == 0 { return; }
socket.write_all(&buf[0..bytes_read]).await.unwrap();
}
});
}
} jemalloc (especially beneficial for multi-threaded programs) by setting:export RUSTFLAGS="-C target-cpu=native -C link-arg=-ljemalloc"
cargo build --releasevalgrind help catch leaks early:valgrind --tool=memcheck --leak-check=full ./target/release/your_programperf: Analyze CPU usage, cache misses, and hot functions:perf record ./target/release/your_program
perf reportcargo install flamegraph
flamegraph ./target/release/your_program # Produces flamegraph.svgulimit -n 65536For a permanent change, edit /etc/security/limits.conf.net.ipv4.tcp_max_syn_backlog to improve network throughput in high‑load scenarios.That wraps up the essential toolkit for both debugging and optimizing Rust code on Ubuntu. The key is to start simple, then layer in more advanced tools as the complexity of your project grows. Happy coding!
下一篇:HDFS监控工具哪个好用
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8