【问题标题】:Remove constant after compilation in Nim在 Nim 中编译后删除常量
【发布时间】:2016-07-11 09:14:43
【问题描述】:

我想将我的 Nim 程序的所有文本和属性存储在单独的文件中,如下所示:

my.properties:

some=Some
say.hello=Hello world

并像这样使用这些键/值:

my_module.nim:

import properties

const
  some = getProperty("some")
  greeting = getProperty("say.hello")

...
# using of those constants

因此,我编写了 properties.nim 模块来在编译期间从属性文件中检索和解析属性。

properties.nim:

import tables, strutils

const content = "./my.properties".staticRead

proc parseProperties (): Table[string, string] =
  result = initTable[string, string]()
  for line in content.splitLines:
    let tokens = line.split("=")
    result[tokens[0]] = tokens[1]

const properties = parseProperties()

proc getProperty* (path: string): string =
  return properties[path]

所以,问题是我的可执行文件中有两个 const 变量(contentproperties),我只在编译期间需要它们.

例如,我怎样才能在编译后删除主题或为此目的编写某种宏?

更新

感谢 zah 这么快的回答,所以我重写了我的 properties.nim

import tables, strutils

let content {.compileTime.} = "./my.properties".staticRead

proc parseProperties (): Table[string, string] {.compileTime.} =
  result = initTable[string, string]()
  for line in content.splitLines:
    let tokens = line.split("=")
    result[tokens[0]] = tokens[1]

let properties {.compileTime.} = parseProperties()

proc getProperty* (path: string): string {.compileTime.} =
  return properties[path]

而且效果很好!

【问题讨论】:

    标签: nim-lang


    【解决方案1】:

    您可以将contentproperty 常量替换为附加了{.compileTime.} pragma 的常规变量。这样的变量会在生成的代码中完全消除。

    【讨论】:

    • 我注意到,如果我用 -d:release 编译我的第一个版本,Nim 的编译器会理解我想要什么并在 C 中生成相同的代码,当我使用 {.compileTime.} pragma
    猜你喜欢
    • 1970-01-01
    • 2016-04-15
    • 2011-11-29
    • 1970-01-01
    • 2019-08-28
    • 2022-08-13
    • 1970-01-01
    • 2021-03-13
    • 2012-06-20
    相关资源
    最近更新 更多