Beginner issue, Control Flow.. for never matches always returns nothing (" "," ")

Beginner here. I'm trying to send this function a temp, for example 0C or 68F and return tuple of 0,C or 68,F but the for statement never matches. I've been having issues with for statements matching so I thought I'd ask. Thanks.

fn temp_from_string(temp: &str) -> (&str, &str) {

    let temp_bytes = temp.as_bytes();
    let mut unit: &str = "";
    let mut temp_unit: &str = "";
    
    for (i , &item) in temp_bytes.iter().enumerate() {

        if item == b'F' || item == b'f' {
           
           unit = &temp[0..i-1]; 
           temp_unit=&temp[i-1..i];

        
        }

        else if item == b'C' || item == b'c' {

           unit = &temp[0..i-1]; 
           temp_unit=&temp[i-1..i];
        
        }

       return (unit,temp_unit)
    };
    return (unit,temp_unit);
}

// I tried this code too with no luck,

fn temp_from_string(temp: &str) -> (&str, &str) {

    let temp_bytes = temp.as_bytes();
    
    for (i , &item) in temp_bytes.iter().enumerate() {

        if item == b'F' || item == b'f' {
           
          return (&temp[0..i-1], &temp[i-1..i]);

        }

        else if item == b'C' || item == b'c' {

          return (&temp[0..i-1], &temp[i-1..i]);
        
        }

       return (" ", " ");
    };
    return (" ", " ");
}

The first return statement in your example is inside the loop body, so your code is inspecting the first byte and then returning without continuing to the rest of the string.

1 Like

Thanks :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.