将字符转换为 &str [英] Converting a char to &str

查看:78
本文介绍了将字符转换为 &str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 match 语句,它返回一个 &str:

I have a match statement which returns a &str:

match k {
    SP_KEY_1 => "KEY_1",
    SP_KEY_2 => "KEY_2",
    SP_KEY_3 => "KEY_3",
    SP_KEY_4 => "KEY_4",
    SP_KEY_5 => "KEY_5",
    SP_KEY_6 => "KEY_6",
    _ => (k as char), // I want to convert this to &str
}.as_bytes()

我尝试先将 char 转换为字符串,然后再取一部分:

I have tried to convert a char to a string first, and then taking a slice of that:

&(k as char).to_string()[..]

但这给了我终生错误:

error[E0597]: borrowed value does not live long enough

声明 (k as char).to_string() 是一个临时值,这是有道理的,因为我可以告诉 to_string() 返回一个克隆.

Stating that (k as char).to_string() is a temporary value, which makes sense as from what I can tell to_string() returns a clone.

我可以将 .to_string() 添加到上面的每个 &str 文字中以生成返回值 String,但这看起来都很丑陋(很多重复的代码),而且可能效率低下,因为 to_string() 克隆了原始字符串切片.

I can add .to_string() to every &str literal above to make the return value String, but that seems both ugly (a lot of repeated code), and probably inefficient, as to_string() clones the original string slice.

具体问题是我如何将 char 变成 &str,但更广泛的问题是是否有更好的解决方案,通常这样做情况.

The specific question is how would I make a char into a &str, but the broader question is that is there a better solution, what is commonly done this situation.

推荐答案

只要不需要从函数中返回&str,就可以完全避免使用char::encode_utf8:

So long as you don't need to return the &str from the function, you can completely avoid heap allocation using char::encode_utf8:

const SP_KEY_1: u8 = 0;
const SP_KEY_2: u8 = 1;
const SP_KEY_3: u8 = 2;
const SP_KEY_4: u8 = 3;
const SP_KEY_5: u8 = 4;
const SP_KEY_6: u8 = 5;

fn main() {
    let k = 42u8;

    let mut tmp = [0; 4];

    let s = match k {
        SP_KEY_1 => "KEY_1",
        SP_KEY_2 => "KEY_2",
        SP_KEY_3 => "KEY_3",
        SP_KEY_4 => "KEY_4",
        SP_KEY_5 => "KEY_5",
        SP_KEY_6 => "KEY_6",
        _ => (k as char).encode_utf8(&mut tmp),
    };

    println!("{}", s);
}

如果您需要更多控制,这可以与闭包配对:

This could be paired with a closure if you needed more control:

fn adapt<F, B>(k: u8, f: F) -> B
where
    for<'a> F: FnOnce(&'a str) -> B,
{
    let mut tmp = [0; 4];

    let s = match k {
        SP_KEY_1 => "KEY_1",
        SP_KEY_2 => "KEY_2",
        SP_KEY_3 => "KEY_3",
        SP_KEY_4 => "KEY_4",
        SP_KEY_5 => "KEY_5",
        SP_KEY_6 => "KEY_6",
        _ => (k as char).encode_utf8(&mut tmp),
    };

    f(s)
}

fn main() {
    adapt(0, |s| println!("{}", s));
    let owned = adapt(0, |s| s.to_owned());
}

或者存储在结构体中以提供一点抽象:

Or stored in a struct to provide a little bit of abstraction:

#[derive(Debug, Default)]
struct Foo {
    tmp: [u8; 4],
}

impl Foo {
    fn adapt(&mut self, k: u8) -> &str {
        match k {
            SP_KEY_1 => "KEY_1",
            SP_KEY_2 => "KEY_2",
            SP_KEY_3 => "KEY_3",
            SP_KEY_4 => "KEY_4",
            SP_KEY_5 => "KEY_5",
            SP_KEY_6 => "KEY_6",
            _ => (k as char).encode_utf8(&mut self.tmp),
        }
    }
}

fn main() {
    let mut foo = Foo::default();
    {
        let s = foo.adapt(0);
    }
    {
        let s = foo.adapt(42);
    }
}

这篇关于将字符转换为 &amp;str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆