处理全局结构中的类型化字符串常量

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

Handling Typed string Constants in a Global Struct

问题

我正在思考如何最好地处理一个包含字符串和数字常量的全局struct集合。

也就是说,我想将所有的字符串和魔法数字收集到一个结构体中,以便可以在全局范围内调用。这样可以防止输入错误,并将所有设置都放在一个地方。我只找到了很多样板代码的解决方案,但最佳解决方案是什么呢?

英文:

I am wondering how best to handle a collection of typed string and number constants in a global struct.

I.e. I like to collect all written strings and magic numbers in one Struct that can be called globally. This is to prevent typing errors and have all settings in one place. I have only found solutions that have a lot of boilerplate, but how is this best solved?

答案1

得分: 1

正如指出的那样,你不能真正使用结构体来实现这个目的。你可以在任何给定的包中声明一组常量,并将它们导出供其他地方使用 - net/http 包可能是最常用的示例,它使用了这种方法(http.MethodGet)。

另一种可能适用于你的方法(如果不了解你的具体用例,很难说更多)是使用枚举类型:

type Building int

const (
    Headquarters Building = iota
    Factory
    Receiving
    Administration
)

func main() {
    fmt.Printf("你在 %d 号楼\n", Factory)
}

playground

我通常喜欢使用类型别名来定义常量,这样我可以将可能的取值范围限制在我想要的范围内:

type Building string

const (
    BuildingHQ      Building = "总部"
    BuildingFactory Building = "工厂"
)

func main() {
    fmt.Printf("你在 %s\n", BuildingHQ)
}

playground

英文:

As pointed out, you cannot really use a struct for this purpose. You can certainly declare a common set of constants within any given package and export them for use elsewhere - the net/http package is probably the most commonly used example of this for both methods (http.MethodGet).

Another method that may or may not work for you (it's tough to say more without knowing specifics of your use case) is the use of an enum:

type Building int

const (
	Headquarters Building = iota
	Factory
	Receiving
	Administration
)

func main() {
  fmt.Printf("You are in building %d\n", Factory)
}

playground

I like using a type alias for constants, generally, so that I can restrict the range of possible values to only those I want:

type Building string

const (
	BuildingHQ      Building = "headquarters"
	BuildingFactory Building = "factory"
)

func main() {
	fmt.Printf("You are in building %s\n", BuildingHQ)
}

playground

答案2

得分: 0

感谢@icza上面的评论。这是go库中处理常量的方式。它们都在全局空间中,所以它们的名称都以Method...和Status...为前缀,与它们相关联。

然后为StatusText(code int)添加了一个方便的方法来返回字符串,但你可以在这个方法中使用任何整数。

package http

// 常见的HTTP方法。
const (
    MethodGet     = "GET"
    MethodPost    = "POST"
    MethodPut     = "PUT"
    MethodDelete  = "DELETE"
    // 跳过的行
)

// HTTP状态码,根据IANA注册。
const (
    StatusContinue           = 100 // RFC 9110, 15.2.1
    StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
    StatusProcessing         = 102 // RFC 2518, 10.1
    StatusEarlyHints         = 103 // RFC 8297

    StatusOK                   = 200 // RFC 9110, 15.3.1
    StatusCreated              = 201 // RFC 9110, 15.3.2
    StatusAccepted             = 202 // RFC 9110, 15.3.3
    StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4
    StatusNoContent            = 204 // RFC 9110, 15.3.5
    // 跳过的行
)

// StatusText返回HTTP状态码的文本。
func StatusText(code int) string {
    switch code {
    case StatusContinue:
        return "Continue"
    case StatusSwitchingProtocols:
        return "Switching Protocols"
    case StatusProcessing:
        return "Processing"
    case StatusEarlyHints:
        return "Early Hints"
    case StatusOK:
        return "OK"

    // 跳过的行

    default:
        return ""
    }
}
英文:

Thanks to @icza comment above. This is how constants are handled in the go lib. They are all in the global space so their names are prefixed by Method... and Status... for those that are related.

Then a convenience method for returning the string is added for the StatusText(code int), but you could use any int in this method.

package http

// Common HTTP methods.
const (
	MethodGet     = "GET"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodDelete  = "DELETE"
	// Skipped lines
)

// HTTP status codes as registered with IANA.
const (
	StatusContinue           = 100 // RFC 9110, 15.2.1
	StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                   = 200 // RFC 9110, 15.3.1
	StatusCreated              = 201 // RFC 9110, 15.3.2
	StatusAccepted             = 202 // RFC 9110, 15.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4
	StatusNoContent            = 204 // RFC 9110, 15.3.5
	// Skipped lines
)

// StatusText returns a text for the HTTP status code.
func StatusText(code int) string {
	switch code {
	case StatusContinue:
		return "Continue"
	case StatusSwitchingProtocols:
		return "Switching Protocols"
	case StatusProcessing:
		return "Processing"
	case StatusEarlyHints:
		return "Early Hints"
	case StatusOK:
		return "OK"

	// Skipped lines

	default:
		return ""
	}
}

huangapple
  • 本文由 发表于 2023年1月25日 21:06:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75234399.html
匿名

发表评论

匿名网友

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

确定