请分享您的观点在2024调查的Clojure现状中!2024 State of Clojure Survey!

欢迎!请查看关于页面以了解更多关于如何使用本站的信息。

0
规格

有关如何验证可选键的问题在Slack上提出了。我原本想把他们指向`s/keys`的文档字符串,但发现这可能需要一些澄清。这个问题的文档字符串

-------------------------
clojure.spec.alpha/keys
([& {:keys [req req-un opt opt-un gen]}])
Macro
  Creates and returns a map validating spec. :req and :opt are both
  vectors of namespaced-qualified keywords. The validator will ensure
  the :req keys are present. The :opt keys serve as documentation and
  may be used by the generator.

  The :req key vector supports 'and' and 'or' for key groups:

  (s/keys :req [::x ::y (or ::secret (and ::user ::pwd))] :opt [::z])

  There are also -un versions of :req and :opt. These allow
  you to connect unqualified keys to specs.  In each case, fully
  qualfied keywords are passed, which name the specs, but unqualified
  keys (with the same name component) are expected and checked at
  conform-time, and generated during gen:

  (s/keys :req-un [:my.ns/x :my.ns/y])

  The above says keys :x and :y are required, and will be validated
  and generated by specs (if they exist) named :my.ns/x :my.ns/y 
  respectively.

  In addition, the values of *all* namespace-qualified keys will be validated
  (and possibly destructured) by any registered specs. Note: there is
  no support for inline value specification, by design.

  Optionally takes :gen generator-fn, which must be a fn of no args that
  returns a test.check generator.

我原本以为会看到一些关于,如果指定的键`:opt`或`:opt-un`存在,将根据该键的规格进行验证的信息。然而,它仅提到它们作为文档。

这似乎需要一些澄清。

1 条回答

+1

选中
 
最佳答案

"除了这些,所有命名空间指定的键的值都将由注册的规格进行验证(可能还会进行结构化)"。

我读到这一点,发现有点微妙。而且这也让我想到,以下情况应该是错误的,因为 `::c` 是一个注册的、命名空间的规范。

(s/def ::c pos-int?)
(s/valid? (s/keys :opt-un []) {:c "3"})

我认为唯一可以解释这一点的方式是,可选键只有在它们存在时才进行验证,这超出了验证所有命名空间限定的键。
by
我想我在那个地方有点笨,但我想这确实包含了。我被“命名空间限定的键”的含糊所指困扰,指的是req、req-un、opt和opt-un向量中的键,而不是映射中的键。无论如何,感谢你那么晚还回答我。
...