The calling of functions

newbie here
From the book THE RUST PROGRAMMING LANGUAGE:

In two different parts of the book, the authors call the following function in (2) different ways:

  1. match f.read_to_string(&mut s) (p.161)
  2. let contents = fs::read_to_string(filename) (p.237)

The author states about version 1, ". . . call the read_to_string method on the file handle in f to read the contents into s." (p. 161)

The author states about version 2, ". . . fs::read_to_string takes the filename, opens that file, and returns a Result of the file's contents."

file_to_string is referred to as a function here -->read_to_string in std::fs - Rust

I'm confused as to why read_to_string is called in two different ways, and why it is that on version 1, the output is assigned to a variable (&mut s) inside the parenthesis and in version 2, the input (filename) is inside the parenthesis.

1 Like

They are actually, two totally independent functions. The 2nd one (as you found) is a top-level function in the standard library's fs module:

std::fs::read_to_string

The other one is a member method of the Read trait (which in this case would be implemented by the concrete File type)

std::io::Read::read_to_string

Note that methods on objects are callable via the single-dot syntax (f.read_to_string) whereas top-level functions are always called via the path syntax using double-colons (std::fs::read_to_string).

In this case, the top-level function is a higher level utility, it combines the process of opening a file from a filename and then reading the contents into a single call.

9 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.