네임스페이스 정의 및 사용
Clojure의 네임스페이스 시스템을 사용하여 코드를 구성하고 이름 충돌을 방지하는 방법을 학습합니다.
네임스페이스 정의 및 사용은(는) CoddyKit의 무료 Clojure Functional Programming & JVM Backend Development 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Clojure Functional Programming & JVM Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Clojure Functional Programming & JVM Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Namespaces Matter
Imagine building a large application with many files and functions. Without organization, you might accidentally use the same name for different things, leading to confusion and errors.
Namespaces in Clojure help you organize your code into logical groups, preventing these naming conflicts and making your projects easier to manage.
Declaring a Namespace
Every Clojure source file starts with a ns declaration. This macro defines the namespace for the code within that file. It usually matches the file's path.
For example, a file named src/my_app/core.clj would typically declare my-app.core as its namespace.
(ns my-app.core)
(defn greet [name]
(str "Hello, " name ". Welcome to " *ns* "))
(defn -main []
(println (greet "CoddyKit user")))Namespace Naming Conventions
Clojure namespaces follow a hierarchical structure, much like Java packages or file paths. They typically use kebab-case (hyphens) for names.
my-project.core: The main entry point or core utilities.my-project.utils: General utility functions.my-project.db.sql: Database interaction logic.
This structure helps keep your code modular and easy to navigate.
Loading Other Namespaces with `require`
To use functions defined in another namespace (or a library), you need to require it. The require declaration typically goes inside your ns form, using a vector of namespace symbols.
Here, we load clojure.string, a built-in library for string manipulation.
(ns my-app.main
(:require [clojure.string]))
(defn -main []
(println (clojure.string/upper-case "hello clojure")))Aliasing Namespaces with `:as`
Typing out full namespace names can be tedious. The :as keyword, used within the :require vector, allows you to create a shorter alias for a required namespace.
This makes your code more concise and readable without sacrificing clarity.
(ns my-app.main
(:require [clojure.string :as str]))
(defn -main []
(println (str/join "-" ["coddy" "kit" "rocks"])))
Selective Loading: `:refer`
Sometimes you only need a few functions from a large namespace, or you want to avoid name clashes. You can use the :refer option within :require to explicitly bring only the specified symbols into your current namespace's scope.
(ns my-app.main
(:require [clojure.set :refer [union]])) ; Only bring 'union' into scope
(defn -main []
(let [set1 #{1 2 3}
set2 #{3 4 5}]
(println "Union of sets:" (union set1 set2))))Clojure Core: Always Available
You might have noticed that you don't need to explicitly require functions like +, map, println, or defn.
This is because these essential functions are part of the clojure.core namespace, which is automatically loaded and referred by every new namespace you create. It's Clojure's standard library.
The `in-ns` Macro (REPL Use)
The in-ns macro changes the current namespace. This is primarily useful when working interactively in the REPL (Read-Eval-Print Loop) to switch contexts without changing your source file.
In general, you won't use in-ns in your application's source code.
(ns my-app.temp)
(defn current-ns-name []
(str *ns*))
(in-ns 'my-app.other-temp)
(defn other-ns-name []
(str *ns*))
(defn -main []
(println "Original NS:" (my-app.temp/current-ns-name))
(println "Switched NS (REPL-like context):" (my-app.other-temp/other-ns-name)))`use`: A Simpler, Riskier Way
Older Clojure code or tutorials might mention the use macro. It's similar to require but automatically brings all public functions from the required namespace into the current one.
While convenient, this can easily lead to naming conflicts (e.g., if two libraries define a count function). For this reason, use is generally discouraged in favor of require with :as or :refer.
Quick Check: Namespace Usage
Which of the following statements about Clojure namespaces and their usage are TRUE?
Recap: Organizing Your Clojure Code
In this lesson, you learned how crucial namespaces are for organizing Clojure projects and preventing naming clashes. We covered:
- Defining a namespace with the
nsmacro. - The importance of hierarchical naming conventions.
- Loading external code using
require. - Creating aliases with
:asfor cleaner code. - Selectively importing symbols with
:refer. - Why
clojure.corefunctions are always available. - The role of
in-nsin the REPL and whyuseis generally avoided.
Mastering namespaces is key to building maintainable and scalable Clojure applications!
자주 묻는 질문
“네임스페이스 정의 및 사용” 강의는 무료인가요?
네 — “네임스페이스 정의 및 사용” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Clojure Functional Programming & JVM Backend Development 강의 전체를 잠금 해제할 수 있습니다. Clojure Functional Programming & JVM Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“네임스페이스 정의 및 사용”에서 뭘 배우나요?
Clojure의 네임스페이스 시스템을 사용하여 코드를 구성하고 이름 충돌을 방지하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Clojure Functional Programming & JVM Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Clojure Functional Programming & JVM Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Clojure Functional Programming & JVM Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“네임스페이스 정의 및 사용” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Clojure Functional Programming & JVM Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Clojure Functional Programming & JVM Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Clojure 매크로 이해하기
- 네임스페이스 정의 및 사용
- 모듈로 코드 구성하기
- 다형성을 위한 프로토콜과 다중 메서드