From the course: Rust Essential Training

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Dangling references

Dangling references - Rust Tutorial

From the course: Rust Essential Training

Start my 1-month free trial

Dangling references

- [Instructor] We've seen how to pass borrowed references as input arguments to a function. Now, let's look at what can happen when you try to return a reference. In this example shown here, the produce fuel function creates a new string to represent the new fuel it's producing. And then it returns a reference to that string. Notice that the return type in the function definition includes the borrow operator. And we're also using the borrow operator on line eight to get a reference to the new fuel variable. Let's try to run this program and it fails to compile. The red error message says something about lifetimes which is a topic we'll cover later in this course. But if we look at the help message, a couple of lines below that it says this functions return type contains a borrowed value, but there is no value for it to be borrowed from. Our problem is that the produce fuel function is creating what's known as a dangling…

Contents