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



目录
打赏
0
相关文章
Node.js中的EventEmitter模块:基本概念、使用方法和常见应用场景
Node.js中的EventEmitter模块:基本概念、使用方法和常见应用场景
186 0
node.js 导入导出模块(CommonJS模块化规范,ES6模块化规范)
node.js 导入导出模块(CommonJS模块化规范,ES6模块化规范)
83 1
Express.js:构建轻量级Node.js应用的基石
**Express.js 概览**:作为Node.js首选Web框架,Express以其轻量、灵活和强大的特性深受喜爱。自2009年以来,其简洁设计和丰富中间件支持引领开发者构建定制化应用。快速开始:使用`express-generator`创建项目,安装依赖,启动应用。示例展示如何添加返回JSON消息的GET路由。Express适用于RESTful API、实时应用等多种场景,社区支持广泛,助力高效开发。
148 1
深入PHP命名空间:代码模块化和避免冲突
【5月更文挑战第26天】在现代PHP开发中,命名空间是实现代码模块化、防止类名和函数名冲突的关键技术。本文将深入探讨PHP命名空间的概念、实现原理及其在实际项目中的应用,帮助开发者更好地理解和使用命名空间,提高代码的可维护性和可扩展性。
Rust代码组织:Package、Crate、Module
Rust代码组织:Package、Crate、Module
【Rust】——package、crate、定义Module
【Rust】——package、crate、定义Module
Node.js—Express使用、Express 路由 、Express 中间件、托管静态资源、使用 Express 写接口、node.js链接sqlite数据库
Node.js—Express使用、Express 路由 、Express 中间件、托管静态资源、使用 Express 写接口、node.js链接sqlite数据库
288 0
Dart中Class、mixin、interface三者间关系及异同
Dart中Class、mixin、interface三者间关系及异同