How to return a instance of a struct that uses a locally declared variable [duplicate]

↘锁芯ラ 提交于 2021-01-28 11:10:28

问题


I am trying to figure out how to declare a variable locally and use it in a value that is being returned. The following is the code that is causing the problem

use std::io;
use std::string::String;
use std::io::Write; // Used for flush implicitly
use topping::Topping;

pub fn read_line(stdin: io::Stdin, prompt: &str) -> String {
    print!("{}", prompt);
    let _ = io::stdout().flush();
    let mut result = String::new();
    let _ = stdin.read_line(&mut result);
    return result;
}

pub fn handle_topping<'a>(stdin: io::Stdin) -> Topping<'a>{
    let name = read_line(stdin, "Topping name: ");
    //let price = read_line(stdin, "Price: ");
    return Topping {name: &name, price: 0.7, vegetarian: false};
}

I have the following struct as a helper

pub struct Topping<'a> {
    pub name: &'a str,
    pub vegetarian: bool,
    pub price: f32,
}

The compiler throws the following error

error: `name` does not live long enough
  --> src/helpers.rs:17:28
   |
17 |     return Topping {name: &name, price: 0.7, vegetarian: false};
   |                            ^^^^ does not live long enough
18 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the body at 14:58...
  --> src/helpers.rs:14:59
   |
14 |   pub fn handle_topping<'a>(stdin: io::Stdin) -> Topping<'a>{
   |  ___________________________________________________________^ starting here...
15 | |     let name = read_line(stdin, "Topping name: ");
16 | |     //let price = read_line(stdin, "Price: ");
17 | |     return Topping {name: &name, price: 0.7, vegetarian: false};
18 | | }
   | |_^ ...ending here

I don't particularly want to change the struct, would much rather get some advice on what it is that I am not understanding.


回答1:


Just switch Topping.name from being a &str to being a String.

You can't return a reference to the result of read_line (a String) because that String will get dropped at the end of handle_topping. You can, however, move ownership of the String into the struct and return a Topping {name: String, veg: bool, ...}.



来源:https://stackoverflow.com/questions/43857098/how-to-return-a-instance-of-a-struct-that-uses-a-locally-declared-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!