gpt4 book ai didi

Clojure:*out* 与 System/out

转载 作者:行者123 更新时间:2023-12-03 00:28:55 24 4
gpt4 key购买 nike

我正在尝试将我用 Java 编写的一个小型控制台程序转换为 Clojure,但我在弄清楚 Clojure 的标准 *out* var 和对象之间的区别时遇到了一些麻烦系统/输出。我的印象是它们是同一件事,但在我的测试过程中它们似乎有所不同。

在我的程序中,我提示用户输入一个数字,并且我希望提示和输入文本位于同一行。在 Java 中,我使用 System.out.print() 打印提示,然后扫描仪读取输入。

以下是我在 Clojure 中第一次尝试类似的事情。尽管 print 函数看起来应该在 read-line 之前触发,但它会立即阻塞输入并在困惑中打印之后的所有内容:

(defn inp1 []
(print "Enter your input: ")
(let [in (read-line)]
(println "Your input is: " in)))

以下是我的下一次尝试,使用*out*。它遇到了与上面的函数相同的问题:

(defn inp2 []
(.print *out* "Enter input: ")
(let [i (read-line)]
(println "You entered: " i)))

在第三次尝试中,我终于直接使用 System/out 让它工作:

(defn inp3 []
(let [o System/out]
(.print o "Enter input: ")
(let [i (read-line)]
(println "You entered: " i))))

我很高兴我终于让它工作了,但我很困惑为什么第三个可以按我想要的方式工作,而前两个却不能。为什么前两个立即阻塞?有人能解释一下吗?

最佳答案

the docs :

*out* - A java.io.Writer object representing standard output for print operations. Defaults to System/out, wrapped in an OutputStreamWriter

...所以,你有一层包装。查看文档 for that layer (强调):

Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered.

...已添加重点。由于OutputStreamWriter会缓冲,因此需要调用.flush来强制写入内容。

关于Clojure:*out* 与 System/out,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36636718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com