Clojure命名空间中use与require的区别

简介: <p><span style="font-size:18px">这个问题的答案来自于stackoverflow,老外人家回答问题就是细心、认真,学习一下。<br> A:Can anyone explain the difference between use and require, both when used directly and as:use and :require in t

这个问题的答案来自于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



目录
相关文章
|
10月前
|
Go
Go 语言的作用域规则及其特点
Go 语言的作用域规则及其特点
153 41
Go 语言的作用域规则及其特点
|
4月前
|
中间件
在 Egg.js 应用中,你可以通过 `this` 关键字来获取上下文
在 Egg.js 应用中,你可以通过 `this` 关键字来获取上下文
64 1
|
3月前
|
存储 Python
Python的命名空间和作用域分析
在Python中,命名空间(Namespace)是用来存储变量名和对象引用之间映射关系的字典,而作用域(Scope)是指程序中变量可以被访问的区域范围。Python中的命名空间是用来存储变量名和对象引用之间映射关系的字典,Python中存在3种命名空间:内置命名空间、全局命名空间和局部命名空间。Python中存在3种命名空间:内置命名空间、全局命名空间和局部命名空间。局部作用域:由局部命名空间定义,在函数内部定义的变量只能在该函数内部访问。在全局命名空间中定义的变量可以在模块内的任何函数或类中直接使用。
39 3
|
2月前
|
Rust
rust 引用了Trait的实现,为什么还需要引入Trait 才能调用实现的方法
rust 引用了Trait的实现,为什么还需要引入Trait 才能调用实现的方法
|
3月前
|
Rust 编译器
Rust代码组织:Package、Crate、Module
Rust代码组织:Package、Crate、Module
|
4月前
|
存储 Python
Python命名空间与作用域详解
Python命名空间与作用域详解
62 0
|
4月前
|
JavaScript 前端开发 开发者
js开发:请解释什么是ES6的let和const关键字,以及它们与var关键字的区别。
ES6引入`let`和`const`替代`var`声明变量。`let`有块级作用域,存在暂时性死区,不进行变量提升,可重新赋值。`const`用于常量,值不可变但引用类型内容可变,同样有块级作用域和暂时性死区。与`var`主要区别在于作用域、变量提升和可变性。这些改进提高了代码的可预测性和安全性。
50 2
|
4月前
|
Rust 编译器
【Rust】——package、crate、定义Module
【Rust】——package、crate、定义Module
【ThinkPHP5.1】如何引用extend的类库
【ThinkPHP5.1】如何引用extend的类库
570 0