User Interaction in Rust through command line
Last updated
Last updated
Before learning about how we can interact with other computers using rust, let's review how we can interact with users.
Refresh pointers concepts from . The idea of the above code is that stdin()
function will return a handle which will listen for user input from the command line. If the input is successfully read then the input variable to refer to that string.
In computers everything is just a string/tape of bits(0 or 1). A turing machine is just an infinite length tape. The types that we use in the programming language are compile time constructs. So whenever your program receives an input it will be in the form of string. It is programmer's responsibility to decode the string into an appropriate type. And if a program wants to ouput something it has to encode that type to a proper string value. We will see this pattern of encoding and decoding whenever the program interacts with outside world, through command line, network calls using APIs etc.,
The idea is to get the string input first and then try to decode it as i32 for example. Note that not all strings can be converted to a number, so we have to do proper error handling. Rust compiler supports that with Result
types. In Python and Java, for example, we will have runtime exceptions. In C atoi
function will interpret the errors as 0, this is really bad because 0 is a valid number.
There are advanced libraries to parse the strings to appropriate types, we will discuss about them later in the course.
This is pretty straight forward and you can read it from .