Just another question on lifetimes

The following code does not compile (playground)

use std::fs::File;
use std::io::{BufReader, BufRead};
use std::path::Path;

fn main() {
    let filename = Path::new("../input");
    let file = File::open(&filename).unwrap();
    let filereader = BufReader::new(file);

    for line in filereader.lines() {
        let moves = line.unwrap().trim().split(",");
        for move_ in moves {
            println!("{}", move_);
    println!("Hello, world!");

apparently the line let moves = line.unwrap().trim().split(","); somehow does not create the list that I expected. I was referred to this part of the documentation: https://doc.rust-lang.org/reference/expressions.html#temporary-lifetimes but I don't really understand it. There is too much unfamiliar jargon in that chapter. If anybody could explain how to fix this kind of thing in broad strokes and with some practical guidelines I would appreciate it.

The issue here is that line is moved when you unwrap() it, and then it isn't stored anywhere else, so it gets dropped and you're left with a dangling reference. The way to fix problems like this in general is to store the intermediate value in a variable:

let line = line.unwrap();
let moves = line.trim().split(",");

So why doesn't it get stored anywhere? Seems pretty obvious that I still want to use it...

Because there isn't any location to store it in the code. Rust, as a system programing language, always prefers explicit and deterministic behavior. Temporary values are always dropped at the end of the root expression, if not stored on the variable. Values stored in the variables are dropped when its lexical scope ends, if not statically determined as moved out.


@Hyeonu So, I have to add an extra let so that I am aware that something is getting stored?

Yes. Rust on principle will not make anything live longer for you (doing so ends up requiring garbage collection in general), so you always have to ensure proper storage, even if it's relatively local and temporary. Variables are semantically meaningful because of that.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.