Friday, July 24, 2020

Where is the infinite loop in the below Rust Program ?

Have you ever wonder how the below  TcpListener Code run infinitely looking for new connections/clients.

Code:
When you run this below program with a Rust compiler or Cargo run, you will see that the program is not ending. How ?


As you noticed , the for loop doesn't have a explicit condition to exit. As far as the Iterator can return values, the "for loop" construct  execute the  statements inside the body. The Iterators can behave like  an infinite loop.But can return "None"(which can be used to exit from "for") , or can return Some values from next method .

Read more to understand how "for loop"  decompose in Rust - https://doc.rust-lang.org/reference/expressions/loop-expr.html

Ok..we understood that there is something called Iterator which can yield for values infinite.

But where is the Iterator here ?

When you look at the TcpListener , it is just a struct. But it has one particular method which implements Iterator trait. 
The connections can be accepted from TcpListener through a  struct called  std::net::Incoming  which is an Iterator.It is hidden(abstracted) behind the method incoming  in this case. As I said earlier  Iterators can yield and ask for values infinite times.





Iterator Trait is implemented on the struct "Incoming"



As you noticed the next method on the Iterator is not going to end. It just keep iterate as far as we are calling incoming method.




Incoming struct accepts connections of TcpListener:



Incoming implementing Iterator trait:




No comments: