rust-lang / rust-lang/rust

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

Open
#141,231 2 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-const-eval A-patterns A-str C-bug T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the behavior using the linked Rust Playground, comparing the const fn byte_string_workaround and string_failure examples. Investigate the compiler handling of matching byte strings versus string literals in constants; done means the string_failure example compiles and behaves like the byte-string workaround.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.