首页 > 解决方案 > Nim 在数组中使用输入无法在编译时评估

问题描述

几天前我刚开始使用 nim 并且无法弄清楚为什么我总是收到此错误:错误:无法在编译时评估:线程计数

import strutils

proc thread_test()=
   echo "test"


echo "How many threads do you want to use?"
var threadcount = readLine(stdin)
echo threadcount
var threads: array[threadcount, Thread[void]]


for i in 0..high(threads):
  threads[i].createThread(thread_test)

joinThreads(threads)
echo "i"

标签: nim-lang

解决方案


First 类型参数array必须是编译时常量(例如,在程序编译时知道,而不是在运行时知道)。所以不可能从输入中读取大小并将其用于array- 您需要有一个动态容器,例如seq.

对此没有特别的解决方法 - 您可以将线程数存储在 中const threadCount = 12,但它也必须是编译时常量。

使用seq您的代码将是

import strutils

proc thread_test()=
   echo "test"


echo "How many threads do you want to use?"
var threadcount = readLine(stdin)
echo threadcount
var threads: seq[Thread[void]]


for i in 0..high(threads):
  threads.add createThread(thread_test)

joinThreads(threads)
echo "i"

推荐阅读