Moving Input to a Function

Hands-on Rust — by Herbert Wolverson (25 / 120)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Capturing User Input | TOC | Trimming Input 👉

You’re frequently going to be asking the user for their name in this chapter. Whenever you have commonly used code, it’s a good idea to move it into a function. This has two advantages: you don’t keep typing the same code, and a single call to what_is_your_name() is less disruptive of the overall flow of your function, which lets you concentrate on the important parts. This is a form of abstraction: you replace detailed code with a function call and move the detail into a function.

When Should I Use a Function?

INFORMATION

Try to use a function when you are typing the same code repeatedly. This is called the DRY principle: Do not Repeat Yourself. Code Complete [McC04] provides an excellent overview of the DRY Principle and its practical application.

You should also consider breaking code up into functions if it becomes very large. It’s much easier to read a shorter function that calls other functions, especially when you come back to a piece of code after a break.

In Hello, World, you declared the main function; making your own functions is similar:

FirstStepsWithRust/hello_yourname_function/src/main.rs

​ ​use​ ​std​::​io​::stdin;

​​①​​fn​ ​what_is_your_name​() ​->​ String {
​​②​ ​let​ ​mut​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.