gpt4 book ai didi

rust - 如何返回使用局部声明变量的结构实例

转载 作者:行者123 更新时间:2023-11-29 08:16:21 25 4
gpt4 key购买 nike

<分区>

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

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

我并不是特别想更改结构,更愿意就我不理解的内容获得一些建议。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com