(case-let) 是一个宏,用于处理形如 {{[:message-tag, arg1, arg2, ...]}} 的消息,并将参数绑定到局部变量。当在 go 块中使用时,它无法正确工作。请注意,一个简单的包含 case 的宏可以正常工作,例如 (defmacro my-case [expr & cases] `(case ~expr ~@cases))。
(附加样品项目)
(case-let) 定义
(ns core-async-bug.macros)
(defmacro case-let [expr & cases]
(let [msg (gensym)]
`(let [~msg ~expr]
(case (first ~msg)
~@(apply concat (for [[key [args & body]] (partition 2 cases)]
[key `(let [~args (rest ~msg)] ~@body)]))))))
ClojureScript 测试代码
(ns core-async-bug.core
(:require-macros [cljs.core.async.macros :refer [go]]
[core-async-bug.macros :refer [case-let]])
(:require [cljs.core.async :refer[
(enable-console-print!)
; go 块中带有手动 case 和 let - 正常工作
(let [c (chan)]
(go
(let [msg (
(case (first msg)
:a (let [[x] (rest msg)] (println "First :a" x))
:b (let [[y] (rest msg)] (println "First :b" y))))
(put! c [:b 123]))
; case-let 在 go 之外工作正常
(case-let [:b 123]
:a ([x] (println "Second :a" x))
:b ([y] (println "Second :b" y)))
; case-let 在 go 内部损坏
(let [c (chan)]
(go
(case-let (
:a ([x] (println "Third :a" x))
:b ([y] (println "Third :b" y))))
(put! c [:b 123]))
浏览器控制台输出
Second :b 123
First :b 123
Third :a 123 <-- 不应该在这里!
Third :b 123