【问题标题】:Slot Options in Common Lisp structure without specifying any slot valueCommon Lisp 结构中的插槽选项,未指定任何插槽值
【发布时间】:2020-04-05 00:14:27
【问题描述】:

有没有办法为结构槽指定一个 slot-option 而不必给它一个默认值?这可能是有益的,例如在定义其他结构将继承的基本结构时,我认为指定 :types 或 :read-only 而不给出初始值会更好看。

由于缺少初始值,以下结构定义会导致错误:

(defstruct s
  (x :type number :read-only t)
  )

【问题讨论】:

    标签: struct common-lisp slots


    【解决方案1】:

    没有。 defstructdefclass 之间的(众多)区别之一是所有结构槽始终都有一个值,并且不指定默认值等同于指定 nil 默认值。

    注意

    对于在 slot-initform 和相应插槽的 :type 选项之间发出类型不匹配的警告的限制是必要的,因为 slot-initform 必须在为了指定插槽选项;在某些情况下,可能不存在合适的默认值。

    在你的情况下,我建议:

    (defstruct s
      (x (error "x is required") :type number :read-only t))
    

    在这种情况下,(make-s) 将发出错误信号,而(make-s :x 10) 将起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 2020-02-15
      • 1970-01-01
      相关资源
      最近更新 更多