2024 Clojure调查问卷中分享您的想法!

欢迎!请参阅关于页面,了解有关此工作的更多信息。

0投票
规范

Slack上提出了有关如何验证可选键的问题。我本来想指向s/keys的docstring,但发现可能需要一些澄清。问题中的docstring

-------------------------
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 整数?)
(s/valid? (s/keys :opt-un [] {:c "3"})

我唯一能解释的是,如果存在于所有命名空间限定键之外,可选键会被验证。
我觉得我在那方面有些笨拙,但我想这确实涵盖了。我被“命名空间限定键”这个术语的含糊不清所困惑,这个术语指的是req、req-un、opt和opt-un向量中的键,而不是map中的键。无论如何,谢谢你的回答那么晚。
...