如何从 char 数组转换 [char;N] 到一个字符串切片 &str? [英] How do I convert from a char array [char; N] to a string slice &str?

查看:22
本文介绍了如何从 char 数组转换 [char;N] 到一个字符串切片 &str?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个固定长度的char数组如:

Given a fixed-length char array such as:

let s: [char; 5] = ['h', 'e', 'l', 'l', 'o'];

如何获得&str?

推荐答案

你不能没有一些分配,这意味着你最终会得到一个 String.

You can't without some allocation, which means you will end up with a String.

let s2: String = s.iter().collect();

问题在于 Rust 中的字符串不是 char 的集合,它们是 UTF-8,这是一种没有每个字符固定大小的编码.

The problem is that strings in Rust are not collections of chars, they are UTF-8, which is an encoding without a fixed size per character.

例如,本例中的数组将占用 5 x 32 位,总共 20 个字节.字符串的数据总共需要 5 个字节(虽然也有 3 个指针大小的值,所以在这种情况下整个 String 会占用更多内存).

For example, the array in this case would take 5 x 32-bits for a total of 20 bytes. The data of the string would take 5 bytes total (although there's also 3 pointer-sized values, so the overall String takes more memory in this case).

我们从数组开始,调用 []::iter,它产生 &char 类型的值.然后我们使用 Iterator::collectIterator<Item = &char> 转换为 String.这使用迭代器的 size_hintString 中预先分配空间,减少额外分配的需要.

We start with the array and call []::iter, which yields values of type &char. We then use Iterator::collect to convert the Iterator<Item = &char> into a String. This uses the iterator's size_hint to pre-allocate space in the String, reducing the need for extra allocations.

这篇关于如何从 char 数组转换 [char;N] 到一个字符串切片 &amp;str?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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