Lesson 9 — Input and Output


0 x00 review

The previous section focused on some of the essentials of type conversion for numeric types in Rust. In this section, let’s look at the inputs and outputs of Rust. I used println! This article is probably the most detailed explanation of Rust’s output on the web.

0x01 Output (print!)

When first introduced to Rust, he wrote Hello World! , we’ve already touched the output println! We already know that we can use it to output strings, numbers, etc., but there are many ways to format output. Let’s take a look.

1. Default output

Println can print string literals directly.

Sample code:

println("hello wolrd");
Copy the code

Code execution result:

Hello, world!
Copy the code

2. Wildcard

The use of the {} wildcard in a string literal refers to the value to be printed, followed by the value to be printed. If there are multiple values, separate them with commas (,).

Sample code:

println!("Today is {} year {} month {} day".2021.6.22);
Copy the code

Code execution result:

Today is2021622Copy the code

3. Wildcard + position

The wildcard {} can be used to specify the position of the value to be printed (starting from 0).

Sample code:

println!("The square of {0} is {0} and the inverse of {0} is {1}".1, -1);
Copy the code

Code execution result:

1The square is1.1The negative of PI is minus PI1
Copy the code

4. Wildcard + named parameter

You can add the named parameter to the wildcard {} character to represent the value of the named parameter to be output.

Sample code:

println!("My name is {name}, I am {age}, and I like {hobby}.", hobby = "Play basketball", name = "Zhang", age = 18);
Copy the code

Code execution result:

My name is Zhang SAN, this year18I like playing basketballCopy the code

5. Wildcard + alignment + alignment width

The wildcard {} can be used to specify the position of the value to be printed (starting from 0). The common symbols are as follows:

format instructions
{:b} The output is converted to binary
{:o} The output is converted to octal
{:x} Output to hexadecimal (lowercase)
{:X} Output converted to hexadecimal (uppercase)
{:e} Scientific Count (lower case)
{:E} Scientific counts (uppercase)
{:p} Output a pointer
{:? } Print the Debug
+} {: If the numeric type is an integer, a + sign is printed before it

Other symbols:

# – This should be a supplementary tag. Often used with other characters.

format instructions
{:#b} Before the output binary0b
{:#o} Add before octal of output0o
{:#x} Add before output hex0x(x is lowercase)
{:#X} Add before output hex0x(x is lowercase)
{: #? } Debug printing with line breaks and indentation

2, > < ^ — define the width

format instructions
6} {6} or {: > The output is right-aligned, and the value of 6 is of type usize
< 6} {: The output is left-aligned, and the value of 6 is of type usize
{: ^ 6} The output is centered and the value of 6 is of type usize
{: any character ^6} The output is centered, the rest is filled with arbitrary characters, and the value of 6 is of type USize
{: any character >6} The output is right-aligned, the rest of the output is filled with arbitrary characters, and the value of 6 is of type USize
{: Any character <6} The output is left justified, the rest is filled with arbitrary characters, and the value of 6 is of type usize

$– Constraint position definition

format instructions
{:1$,”a”,6} The width representation is a value of subscript 1 (the value is of type usize)
{1:0$,6,”a”} The width representation is a value with subscript 0 (the value is of type USize)
{:width$,”a”,width = 6} Use the variable name to define the value of the width

4, 0 – used to fill the width when formatting integers

format instructions
{:08b} Output 8-bit binary, less than 8 bits are filled with zeros
{:08o} Output 8-bit octal, less than 8-bit filled with 0
{:016x} Output hexadecimal 8 bits, less than 16 bits filled with 0

N — often used to express the exact value of a decimal

format instructions
3} {:. After the decimal point accuracy to retain 3 bits (not enough to complement zero, redundant truncation)
{1:.0$} The precision of a value at position 1 is that of a value at position 0.
{:. *} The next two consecutive values, the second value is accurate to the first value (not enough to complement zero, redundant truncation)

Sample code:

	 let a = 31;
    let b = [1.3.5.7.9];

    println!("Binary {:b}", a);
    println!("Octal {:o}", a);
    println!("Hex (lowercase) {:x}", a);
    println!("Hex (uppercase) {:X}", a);
    println!("Scientific count (lowercase) {:e}".100000_f32);
    println!("Scientific count (uppercase) {:E}".100000_f32);
    println!("Print Debug {:? }", b);
    println!("Output punctuation {:+}".5);

    println!("Prefix binary {:#b}", a);
    println!("Octal {:#o}", a);
    println!("Prefix hexadecimal (lowercase) {:#x}", a);
    println!("Prefix hexadecimal (uppercase) {:#X}", a);
    println!("Debug print with line feed and indentation {:#? }", b);

    println!("Right-align with greater-than sign {:>6}{:>6}{:>6}".1.2.3);
    println!("Left-align with less than sign {:<6}{:<6}{:<6}".1.2.3);
    println!("Omit greater than sign right alignment {:6}{:6}{:6}".1.2.3);
    println!("Center aligned {:^6}{:^6}{:^6}".1.2.3);
    println!("Fill any character with center alignment {:-^6}{:*^6}{:1^6}".1.2.3);

    println!("Binary 8-bit zero complement {:08b}", a);
    println!("Octal 8-bit complement zero {:08o}", a);
    println!("Hexadecimal 16-bit complement {:016b}", a);

    println!("{: 1 $}"."a".6);
    println!("{1-0 $}".6."a");
    println!("{:width$}"."a", width = 6);

    println!("Decimal reserved number {:.3}".0.01);
    println!({1:.0$}".3.0.01);
    println!("{} decimals keep 3 digits {:.*} -- keep 4 digits {:.*}".0.01.3.0.01.4.0.10);
Copy the code

Code execution result:

binary11111octal37Hexadecimal (lowercase)1F Hexadecimal (uppercase)1F Scientific count (lowercase)1e5Scientific counts (uppercase)1E5printDebug [1.3.5.7.9] output punctuation +5Prefix binary0b11111The prefix octal0o37Prefix hexadecimal (lowercase)0x1fPrefix hexadecimal (uppercase)0x1FHaving a line feed and indentationDebugprinted1.3.5.7.9,] use the greater-than sign to right justify1     2     3Left-align with less than sign1     2     3Omit the greater-than sign and align it right1     2     3Align center1     2     3Fill any character with center alignment --1---**2* * *113111binary8A zero padding00011111octal8A zero padding00000037hexadecimal16A zero padding0000000000011111

Process finished with exit code 0

Copy the code

6,{and}

It is sometimes possible to include {and} in a string, where {{output {,}} can be printed.

Sample code:

println!("Left parenthesis {{");
println!("Parentheses on the right}}");
println!("Full parentheses {{}}");
Copy the code

0x02 Format (format!)

The use of formatting is basically the same as the use of output. It is used to write formatted text to a string. All println! Of the code above Can be changed to format! , use the format! Often used to format multiple variables as strings. Println will print directly to the screen. I won’t do it again.

0x03 Input (Stdin)

Standard input, also known as console input, is a common type of input. Console input is rarely available, but this is a brief introduction.

Sample code:

let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("read_line error!");
    println!("What you typed was: {}", input);
Copy the code

To explain the code above, we declare a variable of type string, and then use stdin to read the input from the console and save it to the input. If an exception occurs due to a failed read, read_line error! Is displayed. . The string, error handling, will be covered in a later section.

0 x04 summary

This lesson focuses on the output format of Rust. As I said at the outset, this article is probably the most detailed explanation of Rust’s output on the web. Also, print! Structure types cannot be printed by default. To understand the operation of the console input. I don’t know if you noticed, println! There’s an exclamation mark at the end, and I’ve also taken println! It’s called phi is a function. That’s right, it’s not a function, it’s called a macro. The main difference between a macro and a function is that it does not end in an exclamation point. The knowledge about macros will also be introduced in the following chapters, and those who are interested in macros can check the information online in advance.

0x05 This section source code

009 · StudyRust – Code Cloud – Open Source China (gitee.com)

The next section — Rust’s composite data types.