Nim Compiler Version 0.13.0 (2016-01-19) [Windows: i386]
如何在元组中存储对过程的引用:
Job = tuple[every:int, timescale:string, timestr:string, jobfunc:proc]
proc run(job: Job, jobfunc: proc): Job =
result = job
result.jobfunc = addr jobfunc
Run Code Online (Sandbox Code Playgroud)
在run proc jobfunc中:proc被接受了.在元组中,我得到:
错误:'proc'不是具体类型.
那么什么是proc的类型?
[编辑]
我的最终目标是传递一个带有任意参数的函数run.
Atm我已经设法通过使用一个seq[string]但也许一个人知道一种更通用的方式来解决这个问题.
type
Job = tuple[every:int, timescale:string, timestr:string, jobfunc: proc(args:seq[string]) {.gcsafe, locks: 0.}]
proc run(job: Job, jobfunc: proc,args:seq[string]= @[""] ): Job =
# ...
discard
proc myfunc(args:seq[string]) =
echo "hello from myfunc ", args
discard
schedule every(10).seconds.run(myfunc,args= @["foo","uggar"])
Run Code Online (Sandbox Code Playgroud)
在不失去编译时类型安全性的情况下,存储对proc以非泛型方式接受任何参数组合的引用是不可能的.如果你确实需要它(在你的情况下很可能你不需要),你应该使用类似于运行时类型检查的变体类型.然而,对于你的案子来说,它看起来有点过分.我不认为你必须存储用户提供给他的proc的参数,而是存储一个没有参数的proc(闭包),允许你的用户将他的参数包装在一个闭包中.基本上,重写你run的smth就像:
proc run(job: Job, jobfunc: proc()): Job =
# ...
Run Code Online (Sandbox Code Playgroud)
现在您的用户会这样做:
proc myfunc(args:seq[string]) =
echo "hello from myfunc ", args
discard
var myArgs = @["foo","uggar"]
schedule every(10).seconds.run do(): # Do is a sugar for anonymous closure in this context
myfunc(myArgs)
Run Code Online (Sandbox Code Playgroud)