Embed Directive in Nim

Here’s the translation of the Go code to Nim, formatted in Markdown suitable for Hugo:

Our first example demonstrates how to embed files and folders into the Nim binary at compile time. Nim doesn’t have a built-in embed directive like Go, but we can achieve similar functionality using the staticRead pragma.

import os

# Embed the contents of a single file into a string variable
const fileString = staticRead("folder/single_file.txt")

# Embed the contents of a file into a sequence of bytes
const fileByte = staticRead("folder/single_file.txt").toOpenArrayByte(0, int.high)

# Nim doesn't have a direct equivalent to embed.FS, but we can use a sequence of tuples
# to store multiple file contents
const folder = [
  ("folder/single_file.txt", staticRead("folder/single_file.txt")),
  ("folder/file1.hash", staticRead("folder/file1.hash")),
  ("folder/file2.hash", staticRead("folder/file2.hash"))
]

proc main() =
  # Print out the contents of `single_file.txt`
  echo fileString
  echo cast[string](fileByte)

  # Retrieve some files from the embedded folder
  let content1 = folder.findIt(it[0] == "folder/file1.hash")[1]
  echo content1

  let content2 = folder.findIt(it[0] == "folder/file2.hash")[1]
  echo content2

main()

To run this example, you’ll need to create the necessary files and folders:

$ mkdir -p folder
$ echo "hello nim" > folder/single_file.txt
$ echo "123" > folder/file1.hash
$ echo "456" > folder/file2.hash

Then compile and run the Nim program:

$ nim c -r embed_example.nim
hello nim
hello nim
123
456

In this Nim version, we use the staticRead pragma to embed file contents at compile time. Since Nim doesn’t have an exact equivalent to Go’s embed.FS, we simulate it using a sequence of tuples containing file names and their contents.

The findIt iterator is used to retrieve file contents from our simulated embedded filesystem. This approach provides similar functionality to Go’s embed directive, allowing us to include arbitrary files in the Nim binary at compile time.