简体   繁体   中英

Rust: How to set a structs "name" value of type &'static str with a variable

I just started learning rust the other day (so this is my first project in the language). I am trying to create a simple game and I want to have the player input their name and use it here is the player struct:

struct Player {
health: i32,
damage: i32,
sprite: &'static str,
name: &'static str,
gold: i32,
}

and then in my main I call a function that simple returns a player inputted string:

fn main() 
{
let player_name = ask_something("what is your name?");
let player = Player {health: 10, damage: 3, sprite: &player_name.as_str(), name: "player", gold: 0};
}

But that gives me this error:

`player_name` does not live long enough
argument requires that `player_name` is borrowed for `'static`

So my question is how would I do this correctly. Thanks!

You can't have an &'static str from a value you compute at runtime (including a value you get from user input). You'll have to add a lifetime parameter to your struct:

struct Player<'a> {
    health: i32,
    damage: i32,
    sprite: &'a str,
    name: &'a str,
    gold: i32,
}

Or you can use an owning type like String or Box<str> instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM