2017-05-08 6 views
1

変数をローカルで宣言する方法を理解し、返されている値で使用しようとしています。以下は、私がヘルパーローカルで宣言された変数を使用する構造体のインスタンスを返す方法

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 

をスローする必要があり、問題

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

を引き起こしているコードです構造体を変更したいと思っているのですが、私は理解していないことについて何かアドバイスを得るでしょう。

+0

ありがとうございました@Shepmasterが正しい記事を指しています –

答えて

2

Topping.name&strからStringに切り替わるだけです。

そのStringhandle_toppingの終わりに落ちてしまいますので、あなたはread_lineString)の結果への参照を返すことができません。ただし、Stringの所有権を構造体に移動してTopping {name: String, veg: bool, ...}を返すことはできます。

関連する問題