top of page
Search

Rust - variable shadow

Writer: Hareesh Lakshmi NarayananHareesh Lakshmi Narayanan

Rust allows to declare a new variable with the same as previously declared variable. It is referred to as shadowing. Rust also allows using different datatype for the shadow variable.


This is neat because with Java I constantly write code that looks like this,


String getHttpStatusCodeFromResponse(final String responseCode) {
    final String responseCode_trimmed = responseCode.trim();
    final int responseCode_int=                             Integer.parseInt(responseCode_trimmed);
    final String httpStatus = HttpStatus.from(responseCode_int);

    return httpStatus;
}

With Rust,

fn get_httpstatus_from_response(response_code: &str) -> &str {
    let response_code =  response_code.trim();
    let response_code = response_code.parse::<u32>().unwrap();
    let response_code = http_status.from(response_code);
    
    return response_code;
}

Why does this matter?


- Easy readability: Variable names have semantic meaning and important for readability. Suffixing _int, _str in Java is common way to create variables of same thing but with a different data type. This makes reading through large codebases difficult.


I could see this feture resulting in buggy code if not used properly. This feature also seems to have conflicting opinion within rust community, but I like it! +1 to anything that doesn't force me to make up funky variable names!


 
 
 

Recent Posts

See All

Joins

Joining datasets or tables is a common operation these days and Join type determines what rows will be in the result set. This post is a...

Always write Unit Tests

Unit test code should be treated as production code and unit tests should be considered a product feature. Unit tests ensure defects are...

Коментарі


Post: Blog2_Post

hareesh.lakshminarayanan(at)gmail.com

bottom of page