在Golang中,可以使用字面值来引用常量。

huangapple go评论77阅读模式
英文:

Use a literal value to refer to constant in Golang

问题

我已经定义了一个带有类型的常量。我想使用一个变量的值来引用这个常量。(请参考下面的代码)。
一种方法是定义一个键到所需值的映射。还有其他方法可以实现这个吗?


import (
	"fmt"
	"reflect"
)

type Code int

const (
	MY_CONST_KEY Code = 123
)

func main() {
	x := "MY_CONST_KEY"
	//获取x的值作为123
}
英文:

I have defined a constant with a type. I want to use the value of a variable to refer to the constant. (Please refer to the code below).
One way would be to define a map of Key to the required Value. Is there another approach to do this ?


import (
	"fmt"
	"reflect"
)

type Code int

const (
	MY_CONST_KEY Code = 123
)

func main() {
	x := "MY_CONST_KEY"
	//Fetch Value of x as 123
}

答案1

得分: 4

你所要求的是无法实现的。你不能将常量传递给反射包,只能传递它们的字面值。

正如你正确提到的,你可以使用一个映射(map):

package main

import "fmt"

type Code int

var codes = map[string]Code{
	"MY_CONST_KEY":      123,
	"ANOTHER_CONST_KEY": 456,
}

func main() {
	x := codes["MY_CONST_KEY"]
	fmt.Println(x)
}

如果确保映射(map)未导出(codes中的小写c),那么它只能在你的包内部使用,因此包的使用者无法在运行时修改映射。

英文:

There is no way to do what you are asking. You cannot pass constants to the reflect package without instead passing their literal value.

As you correctly mentioned, you can use a map:

package main

import "fmt"

type Code int

var codes = map[string]Code{
	"MY_CONST_KEY":      123,
	"ANOTHER_CONST_KEY": 456,
}

func main() {
	x := codes["MY_CONST_KEY"]
	fmt.Println(x)
}

If you make sure the map is not exported (lower case c in codes), then it will only be available inside your package, so consumers of your package cannot modify the map at runtime.

答案2

得分: 0

代替将x赋值为字符串"MY_CONST_KEY",你可以使用x := MY_CONST_KEY

package main

import (
	"fmt"
)

type Code int

const (
    MY_CONST_KEY Code = 123
)

func main() {
    x := MY_CONST_KEY
	fmt.Println(x) // 这将输出x的值为123
}
英文:

Instead of assigning x to a string, "MY_CONST_KEY", you can do x := MY_CONST_KEY

package main

import (
	"fmt"
)

type Code int

const (
    MY_CONST_KEY Code = 123
)

func main() {
    x := MY_CONST_KEY
	fmt.Println(x) // This fetch the value of x as 123
}

答案3

得分: -1

> 一种方法是定义一个键到所需值的映射。

是的,请这样做。

> 还有其他方法吗?

没有。

英文:

> One way would be to define a map of Key to the required Value.

Yes, do that.

> Is there another approach to do this ?

No.

huangapple
  • 本文由 发表于 2021年6月17日 05:28:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/68010235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定