Warm tip: This article is reproduced from serverfault.com, please click

Declare char for comparison in rust

发布于 2020-12-04 15:19:24

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.

Questioner
road_rash
Viewed
0
pretzelhammer 2020-12-04 23:21:10

Use single quotes for character literals. Fixed:

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

playground