Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Const Char #5

Open
Pspritechologist opened this issue Oct 4, 2024 · 1 comment
Open

Const Char #5

Pspritechologist opened this issue Oct 4, 2024 · 1 comment

Comments

@Pspritechologist
Copy link

Although the concat! macro seems to work fine on char literals (concat!('h', 'e', 'l', 'l', 'o')), it won't seem to accept a const char.
Example:

use constcat::concat;

const MARK: char = '?';
const QUESTION: &'static str = concat!("Why doesn't this work", MARK);

provides the error: no method named 'as_bytes' found for type 'char' in the current scope.

Is there any chance to solve this?

@rossmacarthur
Copy link
Owner

This would be cool to have but I don't think it is a simple fix 🤔. You will have to use const MARK: &'static str = "?" for now.

Some issues:

  • We would need to convert a char in a const context to a byte slice (&[u8]). Static strings can be trivially converted using .as_bytes(), but char is a bit more complex. It seems like you can do it like this, which does not work in a const context yet. 🤯 not sure if there is a better way?
const c: char = '?';

let mut buf = [0u8; 4];
c.encode_utf8(&mut buf);    
let as_bytes = &buf.as_slice()[..c.len_utf8()];
  • The macro needs to be able to handle both types of values. Usually the way to do this is with a trait, but again this has to be done in a const context and const trait methods are not yet supported in Rust.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants