The Nim Tutorial page states:
Lossless Automatic type conversion is performed in expressions where different kinds of integer types are used.
So, I thought that creating an int in the range of a uint8 would allow me to pass it to procs expecingt an uint8.
However, the following code raises the annotated errors:
import random
proc show(x: uint8) {.discardable.} = echo x
let a: int = 255
show(a) # type mismatch: got (int) but expected one of proc show(x: uint8)
let b: uint8 = random(256) # type mismatch: got (int) but expected 'uint8'
show(b)
Run Code Online (Sandbox Code Playgroud)
I am very confused by the first one, which is telling me it expected a procinstead of an int. The second one is clearer, but I expected an autoconversion at this point, since random generates an int in the uint8 range (0..256) (documentation).
Is there a way to convert int to uint8?
该randomPROC定义为返回的int。最大值256在这个例子中的事实没有在类型系统中编码(它可能random是static[int]作为参数)。
“无损转换”意味着较小整数类型的值可以转换为较大整数类型的值(例如 from int8to int32)。在此处的示例中,您尝试在另一个方向执行转换。您可以通过使转换显式来解决错误:
let a = uint8(rand(256))
show a
# or
let b = rand(256)
show uint32(b)
Run Code Online (Sandbox Code Playgroud)
pp 您不需要将discardable编译指示添加到不返回值的 procs 中。