Appearance
原生类型3: exercises/primitive_types/primitive_types3.rs
题目
rust
// primitive_types3.rs
//
// Create an array with at least 100 elements in it where the ??? is.
//
// Execute `rustlings hint primitive_types3` or use the `hint` watch subcommand
// for a hint.
// I AM NOT DONE
fn main() {
let a = ???
if a.len() >= 100 {
println!("Wow, that's a big array!");
} else {
println!("Meh, I eat arrays like that for breakfast.");
}
}
在??
处创建一个至少有100个元素的数组(array)。
题目解析
数组的创建方式主要有以下几种:
- 将数组的值写成在方括号内,用逗号分隔:
let a = [1, 2, 3, 4, 5];
- 通过在方括号中指定初始值加分号再加元素个数的方式来创建一个每个元素都为相同值的数组:
let a = [3; 5];
这里只是让我们创建一个至少有100个元素的数组,我们简单一点来,比如把所有的初始值都设置为Hello world!
:
rust
fn main() {
let a = ???
let a = ["Hello world!"; 100];
if a.len() >= 100 {
println!("Wow, that's a big array!");
} else {
println!("Meh, I eat arrays like that for breakfast.");
}
}
笔记
- 数组中的每个元素的类型必须相同,Rust 中的数组长度是固定的
- 我们可以通过在方括号中指定初始值加分号再加元素个数的方式来创建一个每个元素都为相同值的数组:
let a = [3; 5];