I have this function parse
to parse a HTTP request string. I declare an uninitialized variable method
then later on in the match
statement, I assign it the value GET
or I return from the function with an error.
I would think that upon returning Ok
, the method field would be either populated or the function would return an error before that point, yet the compiler tells me that this is not the case:
error[E0381]: use of possibly-uninitialized variable: `method`
Ok(HttpRequest { s_addr: s_addr, method, scheme: RequestScheme::HTTP })
^^^^^^ use of possibly-uninitialized `method`
pub fn parse(request_string: String, s_addr: SocketAddr) -> Result<HttpRequest, HttpError> {
let mut method: HttpMethod;
for element in request_string.split(" ") {
method = match element {
"GET" => HttpMethod::GET,
_ => {
eprintln!("Couldn't parse word : {}", element);
return Err(HttpError::ParseError);
},
}
}
Ok(HttpRequest { s_addr: s_addr, method, scheme: RequestScheme::HTTP })
}
CodePudding user response:
As @mkrieger1 points out:
What if the
for
loop has 0 iterations?
String
's split
function never returns an empty iterator, so consider using an Option<T>
, then unwrapping the value.
let mut method: Option<HttpMethod> = None;
for element in request_string.split(" ") {
if element != "GET" {
eprintln!("Couldn't parse word : {}", element);
return Err(HttpError::ParseError);
}
method.insert(HttpMethod::Get);
}
Ok(HttpRequest { s_addr, method: method.unwrap(), scheme: RequestScheme::HTTP})
Or, in your case you can just avoid a variable all together.
for element in request_string.split(" ") {
if element != "GET" {
eprintln!("Couldn't parse word : {}", element);
return Err(HttpError::ParseError);
}
}
Ok(HttpRequest { s_addr, method: HttpMethod::Get, scheme: RequestScheme::HTTP})