rspec/rules/S7441/rust/rule.adoc

29 lines
1.0 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
Using `Stdin::read_line` without trimming the newline character can cause runtime issues, especially when parsing the input into another type (e.g., `i32`). The operation will fail if the string contains a trailing newline character, making the code unreliable.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read a line");
let num: i32 = input.parse().expect("Not a number!"); // Noncompliant: The input string may contain a newline character.
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read a line");
let num: i32 = input.trim_end().parse().expect("Not a number!"); // Compliant: Trims the trailing newline character.
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#read_line_without_trim