Search code examples
stringrustcomparisoncharacterliterals

Declare char for comparison


As part of Advent of Code 2020 day 3, I'm trying to compare characters in a string to a specific character.

fn main(){
    let str_foo = 
"...##..#
##.#..#.";
    
    for char in str_foo.chars() {
        println!("{}", char == "#");
    }
    
}

The error I get is expected char, found &str.

I'm struggling to find a clean way to cast either the left or right side of the equality check so that they can be compared.


Solution

  • Use single quotes for character literals. Fixed:

    fn main() {
        let str_foo = 
    "...##..#
    ##.#..#.";
        
        for char in str_foo.chars() {
            println!("{}", char == '#');
        }
    }
    

    playground