Skip to content

Can't match strings in consts, but can match byte strings in consts #141231

Open
@clarfonthey

Description

@clarfonthey

Basically, this feels like an artifical restriction due to the fact that both str::as_bytes and matching on byte strings is possible in constants:

Playground link

const fn byte_string_workaround(x: &str) -> u8 {
    match x.as_bytes() {
        b"hello" | b"world" => 1,
        b"goodbye" | b"nonworld" => 2,
        _ => 3,
    }
}

const fn string_failure(x: &str) -> u8 {
    match x {
        "hello" | "world" => 1,
        "goodbye" | "nonworld" => 2,
        _ => 3,
    }
}

Note that byte_string_workaround compiles fine on stable but string_failure returns an error saying that strings can't be matched in constants.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)A-patternsRelating to patterns and pattern matchingA-strArea: str and StringC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions