Your example is fundamentally flawed.
A library is merely a collection of books. When you say “Libraries are necessary for an educated society” what you’re really saying is “Collections of books are important.”
What you’re saying is: “Collections of books are important and therefore the people’s right to have books shall not be infringed.”
You’re saying: “Books (thing 1) are needed for an educated society, therefore, the right to keep and read books (also thing 1) shall not be infringed.”
Collections of books (libraries) and the books themselves are the same thing.
It’s equivalent to saying, “Cattle herds are necessary for the food supply so therefore the people’s right to keep and eat cows shall not be infringed.”
One doesn’t cause or justify the other because they are both the same thing.
The 2nd Amendment does not say, “Guns in private hands are necessary for the safety of the country, therefore the right to keep and bear arms shall not be infringed.”
You wish it did but it doesn’t.
No, it says that a well-regulated Militia is necessary for the safety of the country.
There is no equivalence in two clauses in the Second Amendment. The need for a well-regulated militia for the security of the country (thing 1) is a completely different thing from the right to keep and bear arms (thing 2).
The 2nd Amendment says that thing 2, the right to keep and bear arms, is needed in order to have thing 1, a well-regulated militia. And in 1791 that was true.
It is no longer true. Thing 2, the right to keep and bear arms, is no longer in any way necessary for thing 1, maintaining a well-regulated militia.
If the Constitution were to say “Trains are vital to the nation (thing 1) so therefore the right of the people to mine and sell coal (thing 2) shall not be infringed” then when locomotives powered by coal ceased to exist that protection for coal mining would be as obsolete as the protection for the right to keep and bear arms is now.