JSRUN 用代码说话

变量

编辑教程

变量

在Clojure中,变量由'def'关键字定义。 这有点不同,其中变量的概念更多地与绑定。 在Clojure中,一个值绑定到一个变量。 在Clojure中需要注意的一个关键点是,变量是不可变的,这意味着为了使变量的值发生变化,它需要被重新销毁和重新创建。

以下是Clojure中的基本类型的变量:

  • short -这用于表示一个短整形,例如:10。

  • int -这用于表示整数,例如:1234。

  • long -这用于表示长整形,例如:10000090。

  • float -这用于表示32位浮点数,例如:12.34。

  • char -这定义了单个字符文字,例如:'/ a'。

  • Boolean -这表示一个布尔值,可以是true或false。

  • String -这些是以字符串的形式表示的文本文本。 例如,“Hello World”。

声明变量

以下是定义变量的一般语法。

语法

(def var-name var-value)

其中'var-name'是变量的名称,'var-value'是绑定到变量的值。

下面是一个变量声明的例子。

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   ;; The below code declares a integer variable
   (def x 1)

   ;; The below code declares a float variable
   (def y 1.25)

   ;; The below code declares a string variable
   (def str1 "Hello")

   ;; The below code declares a boolean variable
   (def status true))
(Example)

变量命名

变量的名称可以由字母,数字和下划线字符组成。 它必须以字母或下划线开头。 大写和小写字母是不同的,因为Clojure,就像Java一样,是一种区分大小写的编程语言。

以下是一些在Clojure中的变量命名的例子。

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   ;; The below code declares a Boolean variable with the name of status
   (def status true)

   ;; The below code declares a Boolean variable with the name of STATUS
   (def STATUS false)

   ;; The below code declares a variable with an underscore character.
   (def _num1 2))
(Example)

-在上面的语句中,由于区分大小写,状态和状态是Clojure中两个不同的变量定义。

上面的例子显示了如何使用下划线字符定义一个变量。

打印变量

由于Clojure使用JVM环境,因此也可以使用'println'函数。 下面的示例显示了如何实现这一点。

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn Example []
   ;; The below code declares a integer variable
   (def x 1)

   ;; The below code declares a float variable
   (def y 1.25)

   ;; The below code declares a string variable
   (def str1 "Hello")
   (println x)
   (println y)
   (println str1))
(Example)

输出

以上示例输出以下结果:

1
1.25
Hello

JSRUN闪电教程系统是国内最先开创的教程维护系统, 所有工程师都可以参与共同维护的闪电教程,让知识的积累变得统一完整、自成体系。 大家可以一起参与进共编,让零散的知识点帮助更多的人。
X
支付宝
9.99
无法付款,请点击这里
金额: 0
备注:
转账时请填写正确的金额和备注信息,到账由人工处理,可能需要较长时间
如有疑问请联系QQ:565830900
正在生成二维码, 此过程可能需要15秒钟