From the course: Debugging Rust Code with AI

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Memory safety exercise

Memory safety exercise

- [Instructor] Rust ownership systems stop memory bugs like dangling pointers. Today, we will debug a common mistake, we'll fix storing a reference to a temporary value using AI tools. Let's dive in. Let's look at our code. We have a data struct with a lifetime parameter. It holds a string reference. Our create_data function tries to return data with a static lifetime. But there is a problem, it creates a temporary string and tries to return the reference to it. Let's check what rust-analyzer says. As we see, we get an error right away. "Cannot return value referencing local variable text, returns a value referencing data owned by the current function. Text is borrowed here." rust-analyzer is like a friend who stops you from making a mistake. In this case, our text variable gets dropped when the function create_data returns. This would leave the reference pointing to nothing. Quite dangerous, correct? Now, let's bring in some AI helpers to fix this. I hover over here, click Quick Fix.…

Contents