在Clojure记录上创建可选字段? [英] Create optional fields on Clojure record?

查看:57
本文介绍了在Clojure记录上创建可选字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我实例化Clojure记录时,如果未设置记录的所有字段,则会收到错误消息.如何指定某些字段为可选字段?

When I instantiate a clojure record I get an error if I do not set all the fields of the record. How can I specify some of the fields to be optional?

推荐答案

defrecord 声明了一个类型和一个构造函数,但该类型实现了clojure map接口.您只需要在声明中放入必填字段.例如,

defrecord declares a type and a constructor, but the type implements the clojure map interface. You just need to put the required fields in the declaration. For example,

(defrecord MyRecord [required1 required2])

(defn make-my-record [r1 r2 & [opt1 opt2]]
  (assoc (MyRecord. r1 r2) :optional1 opt1 :optional2 opt2))

可以像这样使用

user> (make-my-record 1 2)
#:user.MyRecord{:required1 1, :required2 2, :optional2 nil, :optional1 nil}
user> (make-my-record 1 2 :a :b)
#:user.MyRecord{:required1 1, :required2 2, :optional2 :b, :optional1 :a}

这篇关于在Clojure记录上创建可选字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆