📅  最后修改于: 2023-12-03 15:34:46.562000             🧑  作者: Mango
Rust is a modern, performant programming language designed for systems programming. In this tutorial, we will create a Rust program that prints a number square.
Before starting, make sure you have the following installed:
Start by creating a new Rust project using Cargo:
$ cargo new rust-number-square
$ cd rust-number-square
This will create a new Rust project with a default src/main.rs
file containing a simple "Hello, world!" program.
We will modify this file to print a number square.
Open src/main.rs
in your favorite text editor and replace the existing code with the following:
use std::io;
fn main() {
println!("Enter a number:");
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let n: i32 = input.trim().parse().unwrap();
for i in 0..n {
for j in 0..n {
print!("{} ", i * n + j);
}
println!();
}
}
This program prompts the user to enter a number, reads the input from the command line, and prints a number square of size n
x n
.
To run the program, use the following command:
$ cargo run
Here's an example output of the program when run with n = 4
:
Enter a number:
4
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
In this tutorial, we created a Rust program that prints a number square. Rust's performance, memory safety, and expressiveness make it a great choice for systems programming tasks like this one.