douduan4116
2017-09-21 20:03
浏览 1.3k
已采纳

使用os.getenv在golang中声明常量。结果“在os.Getenv(“ MY_SECRET”)不是常量的常量初始化程序”中

If I declare constants as the following I get the error 'const initializer in os.Getenv("MY_SECRET") is not a constant'. Why is this?

New to Go and I see the return type of Getenv is a string, but I don't understand why this wouldn't work as a constant.

const (
    secret     = os.Getenv("MY_SECRET")
    key        = os.Getenv("MY_KEY")
)

图片转代码服务由CSDN问答提供 功能建议

如果我将常量声明为以下内容,则会在os.Getenv(“ MY_SECRET”)中得到错误'const initializer 不是一个常数”。 为什么会这样?

Go的新手,我看到Getenv的返回类型是一个字符串,但是我不明白为什么这不能作为常量工作。

  const(
 secret = os.Getenv(“ MY_SECRET”)
 key = os.Getenv(“ MY_KEY”)
)
  <  / pre> 
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douke1954 2017-09-21 20:11
    已采纳

    Just like the error says, a constant must have a constant value. You cannot set it to the return of a function. It must be evaluated at compile time (e.g. a string literal). If you want to store the values of environment variables looked up at run time, you'll have to store them in variables, not constants.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题