1

I am currently trying my hand on a barebones login system in Rust and I found that while logging in isn't a problem, signing up is. For keeping track of usernames and passwords I use a HashMap<&'static str, &'static str>. For the input for the program I use a TcpStream. The issue here is that incoming bytes from the stream cannot be transformed into a string (slice) that has the static lifetime, which leaves the lifetime requirement unsatisfied:

use std::{
    io::{Read, Write},
    net::{TcpListener, TcpStream},
    collections::HashMap,
};

fn main() {
    let mut user_list: HashMap<&'static str, &'static str> = HashMap::new();

    let list = TcpListener::bind("127.0.0.1:9001").expect("Couldn't set up listener");
    let mut tcp_out = TcpStream::connect("127.0.0.1:9001").expect("Couldn't connect to server");
    let mut tcp_in: TcpStream = list.accept().unwrap().0;

    tcp_out.write(b"V.Molotov").expect("Couldn't send user data");

    let mut username = String::new();
    tcp_in.read_to_string(&mut username).expect("Couldn't read incoming data");

    user_list.insert(&username[..], "Som_Gen_ricPassw_rd"); // Error: `username` doesn't live long enough!
}

Is there a way to append stream data to the HashMap, or is there some other approach I should consider?

Francis Gagné
  • 60,274
  • 7
  • 180
  • 155
V.Molotov
  • 59
  • 5
  • [Playground of the code in question](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=73b38b0734cef18f7b713eb68744fa2d) – Elias Holzmann Aug 17 '21 at 11:32
  • You cannot make them stataic. Also in that case you must not use string slices, but `String` objects. – Svetlin Zarev Aug 17 '21 at 11:34
  • @SvetlinZarev Thank you for the comment. Are there other situations where I should use `String` instead of `&str`? I tend to prefer the latter because I assume they take up less space and time to work with. – V.Molotov Aug 17 '21 at 11:37
  • Take a look at [this question](https://stackoverflow.com/questions/24158114/what-are-the-differences-between-rusts-string-and-str), but the short version is use `String` if you want ownership. – kopecs Aug 17 '21 at 13:02

0 Answers0