在Rust中初始化字符串数组 [英] Initializing an array of strings in Rust

查看:462
本文介绍了在Rust中初始化字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个固定大小的可变数组.稍后在程序中初始化元素.如何初始化数组?

I want to create a mutable array of a fixed size. The elements are initialized later in the program. How do I initialize the array?

我尝试这样做:

let mut array: [String; 126] = [String::new(); 126];

它给了我错误:

the trait bound 'std::string::String: std::marker::Copy' is not satisfied
the trait 'std::marker::Copy' is not implemented for 'std::string::String'

如何使用新字符串初始化数组?

how do I initialize the array with new strings?

推荐答案

目前,使用固定大小的大型数组几乎没有好处.它们没有实现其他序列类型那么多的特征.

At the moment, there is little benefit from the use of large fixed size arrays. They do not implement as many traits as other sequence types.

尤其是,在这里使用Default可能会很有用,但仅可用于不超过32个的数组:

In particular, having Default would have been useful here, but it's only implemented for arrays up to 32:

let array: [String; 32] = Default::default();

任何超出此数目的数字都将无法编译,因为目前,Rust在数组大小上不是通用的,并且Default的这32种实现都是手动添加的.

Any number over that will fail to compile because, at the moment, Rust is not generic over the size of the array, and these 32 implementations of Default were sort-of added manually.

我们可以使用其他容器类型(例如Vec)来克服这一问题:

We can overcome that with alternative container types, such as Vec:

let mut array: Vec<String> = vec![String::new(); 126];

但是,当然,根据您的用例,您还可以考虑变懒,仅使用

But of course, depending on your use case, you might also consider going lazy and only collecting the final outcomes using the Iterator API.

这篇关于在Rust中初始化字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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