Why does it use Box::new to place a BufReader object into a Box?
Why doesn't just simply use the return value of BufReader::new?
let mut buf: Box<dyn BufRead> = Box::new(BufReader::new(fs::File::open("file.txt")?));
Why does it use Box::new to place a BufReader object into a Box?
Why doesn't just simply use the return value of BufReader::new?
let mut buf: Box<dyn BufRead> = Box::new(BufReader::new(fs::File::open("file.txt")?));
Your misunderstanding could come from two parts in this snippet: the use of a trait object, and the use of a Box.
Notice that the type declared for the variable buf (ie. Box<dyn BufRead>) does not match the type of the value it is assigned to (ie. Box<BufReader<_>>). That is, Rust performs an "implicit" cast for you. The exact cast that is performed is BufReader<_> is casted to a dyn BufRead, which is possible because BufReader<_>: BufRead.
If you don't know that dyn Trait means, given a trait Trait, please read about trait objects. One peculiarity of trait objects is that they are never Sized, ie. the compiler can never know their size in advance, simply because a type with any size could be created, implement a given trait, and thus be a possible concrete type for a trait object. For this reason, you need to allocate it on the heap, which is basically what Box does.
A Box is a, basically, an owned pointer, that is, it's a pointer to data allocated on the heap, but with the peculiarity that whomever owns the box also owns its content (which is not the case, for instance, of &T). This also means that instantiating a new Box takes care of allocating directly on the heap. If you want more details about memory allocation on the heap vs on the stack in Rust, I would recommend reading about it.