Clojure命名空間中use與require的區別

這個問題的答案來自於stackoverflow,老外人家回答問題就是細心、認真,學習一下。
A:Can anyone explain the difference between use and require, both when used directly and as:use and :require in the ns macro?
B:require loads libs (that aren't already loaded), use does the same plus it refers to their namespaces with clojure.core/refer (so you also get the possibility of using :exclude etc like withclojure.core/refer). Both are recommended for use in ns rather than directly.
A:If I require lib foo, then to use bar in foo, I'd have to write foo/bar every time, right? Why would you want to load a lib in ns but then not refer it into the ns? I guess you might be worried about collisions, and you don't want to bother having to reconcile them, right?
B:not having to reconcile collisions is a good point, and more generally there's a programming style which says "namespaces are a honking great idea, we should have more of them" (from "The Zen of Python") -- so e.g. that style recommends not using "using namespace foo;" in C++, so that readers and maintainers of the code won't have to worry "where does this bar come from" but see a more explicit foo::bar instead. require (vs use) supports this "explicit namespaces" style.


總結一下:

use就是在當前項目中引用別的項目時,通過clojure.core/refer把其他項目的函數變量等引入當前項目的工作空間中來,這樣在引用其他項目中的函數時就不用再寫項目名了。
require比use功能少些,不把別的項目引入當前工作空間,在引用別的項目的函數時需要寫全項目名+函數名。

至於其中的原因,老外說的很清楚了。that style recommends not using "using namespace foo;" in C++, so that readers and maintainers of the code won't have to worry 

擴展閱讀:

http://stackoverflow.com/questions/3408076/difference-in-clojure-between-use-and-require

http://stackoverflow.com/questions/871997/difference-between-use-and-require



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章