Chuyển đến nội dung

Bài 7 · Basics and Types

Type Conversions and Distinct Types

Convert between Nim types safely with int(), float(), $ and parseInt, understand cast, make type aliases, and use distinct types to stop unit mix-ups at compile time.

Nim is strict about types. It will not quietly turn an integer into a float or a string into a number. That strictness prevents bugs, but it means you need to know the conversion tools. This lesson covers explicit conversion, parsing text, the dangerous cast, and a feature that makes Nim code safer than most languages: distinct types.

Nim code here is read-only (the compiler cannot run on this site). The C stand-ins are runnable.

Converting between numeric types

Write the target type like a function:

NIM
let whole = 7
let ratio = float(whole) / 2      # 3.5
let again = whole.float / 2       # same, using call syntax
let cut   = int(3.99)             # 3, truncates toward zero
let big   = 300
let small = uint8(big)            # raises RangeDefect at run time

Conversions check the range (in builds with checks on). Turning 300 into a uint8 fails instead of silently becoming 44. This is one reason to prefer conversion over cast.

To round instead of truncate, use round from std/math:

NIM
import std/math
echo int(round(3.6))     # 4

Converting to and from strings

NIM
import std/strutils

echo $42                  # "42"     (any value to string)
echo $3.5                 # "3.5"
echo parseInt("123") + 1  # 124
echo parseFloat("2.5")    # 2.5
echo parseBool("true")    # true

parseInt raises a ValueError for text like "12x". Handle bad input with try (exceptions lesson). The standard library also has std/parseutils for parsing without exceptions.

flowchart LR
  S["string"] -- "parseInt / parseFloat" --> N["int / float"]
  N -- "$" --> S
  I["int"] -- "float(i)" --> F["float"]
  F -- "int(f) (truncates)" --> I

Caption: the usual conversion paths between text and numbers.

Type aliases

A plain type line with another type's name creates an alias. It is only a new name; the compiler treats both as the same type:

NIM
type
  Celsius = float
  Count = int

var temp: Celsius = 21.5
var plain: float = temp     # fine, same type

Aliases document intent but do not protect you.

cast: reinterpret the bits

NIM
let bits = cast[uint64](1.0)    # the raw IEEE bits of 1.0
echo toHex(bits)                # 3FF0000000000000

cast[T](x) tells the compiler "treat these bytes as type T" with no checks. It is meant for low-level code (hardware, serialization, FFI). Do not use it to convert values; use T(x) for that.

Distinct types

A distinct type is a brand-new type that shares the representation of an existing type but none of its operations. This is the tool for preventing mix-ups like adding meters to seconds:

NIM
type
  Meters  = distinct float
  Seconds = distinct float

let distance = Meters(100.0)
let time = Seconds(9.58)

echo distance + time        # compile error: no `+` for Meters and Seconds

Even distance + distance fails at first, because a distinct type does not inherit operators. You choose which ones to bring over with the borrow pragma:

NIM
proc `+`(a, b: Meters): Meters {.borrow.}
proc `<`(a, b: Meters): bool {.borrow.}
proc `$`(a: Meters): string {.borrow.}

echo distance + Meters(5.0)      # 105.0

Now Meters + Meters works, but Meters + Seconds still does not. There is no run-time cost: after compilation a Meters is just a float. You can pull the value back out with a conversion, float(distance).

You can also borrow all of a base type's operations with a template or define helper operators by hand (for example, Meters * float giving Meters). Distinct types are also great for IDs: type UserId = distinct int makes it impossible to pass an order number where a user ID is expected.

Tool Checks values? Prevents mixing types? Use for
T(x) conversion yes (range) n/a numbers, ordinals
cast[T](x) no no low-level bits
alias type A = B no no readability
distinct n/a yes units, IDs, handles

Stand-in: a distinct type in C

C gives you a close approximation: wrap the value in a one-member struct. The compiler then refuses to mix the two struct types. This stand-in is C, not Nim.

C Stand-in: distinct meters and seconds as structs

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Try uncommenting the commented line: the C compiler rejects it, the same way Nim rejects Meters + Seconds.

Stand-in: checked narrowing

Nim's uint8(300) raises a RangeDefect. This stand-in performs the same check by hand.

C Stand-in: range-checked conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last line shows what a raw C cast does, and why Nim's checking conversion is friendlier.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does int(3.99) return?

    Converting a float to an integer truncates toward zero. Use round first if you want rounding.
  2. 2. What is the main purpose of a distinct type?

    A distinct type is incompatible with its base type until you borrow or define operations.
  3. 3. Which call turns the text "123" into an integer?

    parseInt from std/strutils parses text; the others do not or would be wrong.
  4. 4. Why is cast risky?

    cast does no checks; it is for low-level work, not everyday conversion.

Summary

  • Convert numbers with T(x); range checks protect you. Use $ and parseInt/parseFloat for text.
  • A type alias is only a new name; distinct makes a truly separate type.
  • Borrow operations for a distinct type with {.borrow.} and define the rest yourself.
  • cast reinterprets bits and is for low-level code only.

Next: Enums and subranges

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.