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"

解决方法

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"