Rust book chapter 2: Value paased by Ok variant of Result

Hi,

I'm just starting with the rust book and am kind of stuck with a last statement of the ** Handling Potential Failure with Result** section (highlighted in bold):

Values of the Result type, like values of any type, have methods defined on them. An instance of Result has an expect method that you can call. If this instance of Result is an Err value, expect will cause the program to crash and display the message that you passed as an argument to expect . If the read_line method returns an Err , it would likely be the result of an error coming from the underlying operating system. If this instance of Result is an Ok value, expect will take the return value that Ok is holding and return just that value to you so you can use it. In this case, that value is the number of bytes in the user’s input.

I don't understand why the value is the number of bytes in the user's input and not the actual value inputted by the user, could someone please clarify?

Please bear in mind that I am super new to rust and programming in general.

Thanks in advance! :slight_smile:

Simón

The methods in the Read trait take a mutable reference to a buffer as an argument, and return a Result which contains either an Ok value with the number of bytes written to that buffer, or an Err value with some sort of I/O error that occurred when reading.

The reason they don't return the actual value is because it's often a good idea to reuse some buffer when doing many reads at once, which saves us from having to free that buffer on every read call.

1 Like

Because the line input of the user is placed into the string passed by mutable reference to the read() method. You could just read the documentation.

(read_line, not read.) But neither method's documentation explains why they take an out parameter rather than returning the data, which is an entirely reasonable question for someone new to Rust and/or programming to ask.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.