什么时候该使用局部变量?

今天我看到spacemacs的一段代码:

(when (spacemacs/system-is-mac)
    (let ((gls (executable-find "gls")))
      (when gls
        (setq insert-directory-program gls
              dired-listing-switches "-aBhl --group-directories-first"))))

这里用let的原因是啥?

谢谢各位

没有什么特殊的吧,看起来更清楚,不用也完全可以

我的理解,没有什么特殊的原因:

  1. 下方有两处引用,用一个变量指代代码更简洁一点
  2. 避免了多次查找二进制

在下边出现两次,这就值得使用变量代替了,何况 executable-find 是比较耗时的操作:

(executable-find COMMAND &optional REMOTE)

Search for COMMAND in ‘exec-path’ and return the absolute file name.
Return nil if COMMAND is not found anywhere in ‘exec-path’.  If
REMOTE is non-nil, search on the remote host indicated by
‘default-directory’ instead.

好吧……我看叉了,setq后面的gls没有双引号……对不起

第一性能问题, 第二不污染命名空间, 把临时变量封锁在 let 的作用域内.

这纯属我看漏了……

还可以写成:

(and (spacemacs/system-is-mac)
     (executable-find "gls")
     (setq insert-directory-program "gls"
           dired-listing-switches "-aBhl --group-directories-first"))

(executable-find "gls") 返回 Non-nil 能确保不是绝对路径的 gls 可以使用。

我就是这点看漏了……我以为spacemacs是如此写的……

但是我发现这也有问题……就是gls的command name如果不是gls就麻烦了……虽然这是基本不可能发生的事情……

emm, 然后你发现这段代码没用了,因为它还放在exec-path-from-shell里面。。。跟作者提了好久,没反应

没用了?怎么回事请……

因为那个包被spacemacs给移除了啊。。

你越说我越不明白了……哪个包?

exec-path-from-shell这个包被移除了啊,然而你说的那段gls的代码还在post-init-exec-path-from-shell里面啊。