SBCL 警告变量已定义但从未使用过

SBCL warning that a variable is defined but never used

我从 sbcl 编译器收到警告,变量已定义但未使用。编译器是对的。我想摆脱警告,但不知道该怎么做。这是一个例子:

(defun worker-1 (context p)
  ;; check context (make use of context argument)
  (if context
      (print p)))

 (defun worker-2 (context p)
   ;; don't care about context
   ;; will throw a warning about unused argument
   (print p))

 ;;
 ;; calls a given worker with context and p
 ;; doesn't know which arguments will be used by the
 ;; implementation of the called worker
 (defun do-cmd (workerFn context p)
   (funcall workerFn context p))

 (defun main ()
    (let ((context ()))
     (do-cmd #'worker-1 context "A")
     (do-cmd #'worker-2 context "A")))

do-cmd-函数需要实现特定接口 f(context p) 的工作函数。

sbcl 编译器抛出以下警告:

in: DEFUN WORKER-2
;     (DEFUN WORKER-2 (CONTEXT P) (PRINT P))
;
; caught STYLE-WARNING:
 ;   The variable CONTEXT is defined but never used.
;
; compilation unit finished
;   caught 1 STYLE-WARNING condition

你需要声明参数是故意的ignored.

(defun worker-2 (context p)
  (declare (ignore context))
  (print p))
如果您 使用该变量,

ignore 也会发出警告信号。要在这两种情况下抑制警告,您可以使用声明 ignorable,但这应该只用于宏和其他无法 可能 确定变量是否会出现的情况在声明时使用。

如果您还不熟悉declare,请注意它不是运算符,只能出现在certain locations中;特别是,它必须位于 defun 正文中所有表单之前,尽管它可以位于文档字符串的上方或下方。