0

I am not certain in which way I should represent related string constants, namely language codes, in Go.

  1. The only occurrence in the standard library, of which I am aware, uses untyped string constants and prefixes the variable names with the "type".

    const LanguageEnglish = "en"
    
  2. There is the possibility to declare an extra type.

    type Language string 
    
    const English Language = "en"
    // or
    const LanguageEnglish Language = "en"
    

    But any arbitrary string can be converted to the type anyways, so I can not remark any advantage.

    Language("en")
    

Essentially two questions arose from the prior observations:

  1. Should the string constants’ names be prefixed by their "type"?

  2. What are the benefits of using a custom type in contrast to untyped string constants?

  • 1
    Possible duplicate https://stackoverflow.com/q/14426366/13860 – Jonathan Hall Aug 04 '19 at 10:58
  • I will correct the terminology, but the question is not a duplicate of the mentioned one (especially regarding naming conventions). –  Aug 04 '19 at 11:30
  • *"Are there any official conventions, especially regarding the naming?"* The only official documentation on naming conventions, that I know of, can be found [here](https://golang.org/doc/effective_go.html#names). No special mention on naming constants though, so you're free to choose the naming approach that best suits your need. – mkopriva Aug 04 '19 at 11:59
  • *"... so I can not remark any advantage."* You can put methods on your type, you cannot do the same with types you haven't declared yourself, e.g. `string`. For example [this code](https://golang.org/doc/effective_go.html#constants) couldn't implement the stringer interface if it used `float64` directly as the type of the enums. – mkopriva Aug 04 '19 at 11:59
  • 1
    Possible duplicate: https://stackoverflow.com/q/22688906/13860 – Jonathan Hall Aug 04 '19 at 12:10
  • The stdlib uses untyped string consts [all](https://golang.org/pkg/net/http/#pkg-constants) [over](https://golang.org/pkg/os/#pkg-constants) [the](https://golang.org/pkg/net/rpc/#pkg-constants) [place](https://golang.org/pkg/time/#pkg-constants) – Jonathan Hall Aug 04 '19 at 12:18
  • Are you aware of [x/text/language](https://godoc.org/golang.org/x/text/language)? It doesn't answer your actual question, but may obviate it. When dealing with languages, this package would provide the most idiomatic and standard way of using language tags. – Jonathan Hall Aug 04 '19 at 12:23
  • Thanks for the quick responses! @Flimzy Yes, it isn't. But "LanguageEnglish" is constructed by the same naming scheme as "StatusOK". –  Aug 04 '19 at 13:06
  • You shouldn't use `Language("en")` if you have a type for your constants. Typically you use `switch`, so you won't get arbitrary string for `Language` type. – tetafro Aug 04 '19 at 17:27

0 Answers0