如何返回使用本地声明变量的结构实例 [英] How to return a instance of a struct that uses a locally declared variable

查看:43
本文介绍了如何返回使用本地声明变量的结构实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何在本地声明一个变量并在返回的值中使用它.以下是导致问题的代码

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};
}

我有以下结构作为帮手

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

编译器抛出以下错误

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.

推荐答案

只需将 Topping.name&str 切换为 String.

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

您不能返回对 read_line(一个 String)结果的引用,因为 String 将在结束时被删除handle_topping.但是,您可以将 String 的所有权移动到结构中并返回 Topping {name: String, veg: bool, ...}.

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, ...}.

这篇关于如何返回使用本地声明变量的结构实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆