登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-02-08 21:42:22 183浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《管理全局结构中的字符串常量类型》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我想知道如何最好地处理全局 struct 中类型化 string 和数字常量的集合。

即我喜欢将所有书面字符串和幻数收集在一个可以全局调用的结构中。这是为了防止输入错误并将所有设置集中在一处。我只找到了有很多样板的解决方案,但是如何最好地解决这个问题?


正确答案


正如所指出的,您不能真正使用结构来达到此目的。您当然可以在任何给定包中声明一组通用常量,并将它们导出以在其他地方使用 - net/http 包可能是这两种方法最常用的示例 (http.methodget)。

另一种可能适合你也可能不适合你的方法(在不知道你的用例的具体情况的情况下很难说更多)是使用 enum

type building int

const (
    headquarters building = iota
    factory
    receiving
    administration
)

func main() {
  fmt.printf("you are in building %d\n", factory)
}

playground

通常,我喜欢对常量使用类型别名,这样我就可以将可能值的范围限制为我想要的值:

type building string

const (
    buildinghq      building = "headquarters"
    buildingfactory building = "factory"
)

func main() {
    fmt.printf("you are in building %s\n", buildinghq)
}

playground

感谢上面的@icza评论。这就是 go lib 中处理常量的方式。它们都在全局空间中,因此对于相关的名称,它们的名称以 method... 和 status... 为前缀。

然后为 statustext(code int) 添加一个返回字符串的便捷方法,但您可以在此方法中使用任何 int。

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 ""
    }
}

以上就是《管理全局结构中的字符串常量类型》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>