使用 vec 初始化向量!宏并用现有数组中的值填充它
Initialize vector using vec! macro and fill it with values from existing array
如何使用 vec!
宏初始化新 Vector 并自动用现有数组中的值填充它?这是代码示例:
let a = [10, 20, 30, 40]; // a plain array
let v = vec![??]; // TODO: declare your vector here with the macro for vectors
除了 ???
个字符,我可以填写什么(语法方面)?
由于Vec<T>
impls From<[T; N]>
, it can be created from an array by using the From::from()
method or the Into::into()
方法:
let v = Vec::from(a);
// Or
let v: Vec<_> = a.into(); // Sometimes you can get rid of the type annoation if the compiler can infer it
vec![]
宏不适用于此;它旨在从头开始创建 Vec
s,就像数组文字一样。您可以使用 vec![]
宏,而不是创建数组并转换它:
let v = vec![10, 20, 30, 40];
您也可以使用to_vec
方法:
let a = [10, 20, 30, 40]; // a plain array
let v = a.to_vec();
A 根据评论,请注意它克隆了元素,因此向量项应实现 Clone
。
如何使用 vec!
宏初始化新 Vector 并自动用现有数组中的值填充它?这是代码示例:
let a = [10, 20, 30, 40]; // a plain array
let v = vec![??]; // TODO: declare your vector here with the macro for vectors
除了 ???
个字符,我可以填写什么(语法方面)?
由于Vec<T>
impls From<[T; N]>
, it can be created from an array by using the From::from()
method or the Into::into()
方法:
let v = Vec::from(a);
// Or
let v: Vec<_> = a.into(); // Sometimes you can get rid of the type annoation if the compiler can infer it
vec![]
宏不适用于此;它旨在从头开始创建 Vec
s,就像数组文字一样。您可以使用 vec![]
宏,而不是创建数组并转换它:
let v = vec![10, 20, 30, 40];
您也可以使用to_vec
方法:
let a = [10, 20, 30, 40]; // a plain array
let v = a.to_vec();
A 根据评论,请注意它克隆了元素,因此向量项应实现 Clone
。