GeckStar
GeckStar

Reputation: 1156

Converting an int type to a uint8

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)

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?

Upvotes: 4

Views: 3096

Answers (1)

zah
zah

Reputation: 5384

The random proc is defined to return an int. The fact that the max value is 256 in this example is not encoded in the type system (it could have been if random was taking static[int] as an argument).

"lossless conversion" means that a value of a smaller integer type can be converted to a value of a larger integer type (e.g. from int8 to int32). In the examples here, you are trying to perform a conversion in the other direction. You can get around the errors by making the conversions explicit:

let a = uint8(rand(256))
show a
# or
let b = rand(256)
show uint32(b)

p.p. you don't need to add the discardable pragma to procs which don't return values.

Upvotes: 6

Related Questions