wtfm_rs_echo_hello_world/lib.rs
1#![doc(html_playground_url = "https://play.rust-lang.org/")]
2//! # Get the ouput from `echo Hello, world!`
3//!
4//! ```
5//! use std::process::Command;
6//! let output = Command::new("echo")
7//! .arg("Hello,")
8//! .arg("world!")
9//! .output()
10//! .expect("Failed to execute command");
11//! let output_1 = String::from_utf8_lossy(&output.stdout).to_string();
12//! assert_eq!(format!("{}", output_1), "Hello, world!\n");
13//! let output_2 = String::from_utf8(output.stdout).expect("Format error");
14//! assert_eq!(format!("{}", output_2), "Hello, world!\n");
15//! ```
16//! [std::process::Command]
17//!
18//! [String::from_utf8]
19//!
20//! [String::from_utf8_lossy]
21//!
22//! After RTFM, we might want to use [str::from_utf8]:
23//!
24//! ```
25//! use std::process::Command;
26//! let output = Command::new("echo")
27//! .arg("Hello,")
28//! .arg("world!")
29//! .output()
30//! .expect("Failed to execute command");
31//! let hello_world = str::from_utf8(&output.stdout).expect("Format error");
32//! assert_eq!(hello_world, "Hello, world!\n");
33//! ```
34
35use std::process::Command;
36
37pub fn echo_hello_world() -> String {
38 let output = Command::new("echo")
39 .arg("Hello,")
40 .arg("world!")
41 .output()
42 .expect("Failed to execute command");
43 String::from_utf8(output.stdout).expect("Format error")
44}
45
46pub fn echo_hello_world_v2() -> String {
47 let output = Command::new("echo")
48 .arg("Hello,")
49 .arg("world!")
50 .output()
51 .expect("Failed to execute command");
52 str::from_utf8(&output.stdout)
53 .expect("Format error")
54 .to_string()
55}
56
57#[cfg(test)]
58#[test]
59fn test_echo_hello_world() {
60 assert_eq!(format!("{}", echo_hello_world()), "Hello, world!\n");
61}
62
63#[test]
64fn test_echo_hello_worl_v2() {
65 assert_eq!(echo_hello_world_v2(), "Hello, world!\n");
66}