Documentation ¶
Overview ¶
Package i18n contains internationalization and localization utilities.
Translations are handled by the Dict type and its Get method, whose type is captured by Translator. Dict presents a very (memory) compact and efficient translation model, while preserving the flexibility of a map with one tiny compromise: if something translates into the empty string, the Empty constant must be used (because generally the empty string in a Dict denotes a missing translation).
Locales must be modeled with integers, where 0 denotes your default, fallback locale. For example:
// Define your locales const ( EN = iota DE HU )
Generally Dict values are not needed to be retained, only their Get method value:
var Day = Dict{EN: "Day", DE: "Tage"}.Get
Where Day is of type Translator, and can be called like this:
fmt.Println("Day in English:", Day(EN))
Example ¶
package main import ( "fmt" "github.com/icza/gox/i18n" ) // Define your locales const ( EN = iota HU DE GR ) var Monday = i18n.Dict{ EN: "Monday", DE: "Montag", HU: i18n.Empty, // We want this to be empty }.Get var Introduce = i18n.Dict{ EN: "My name is %s, and I'm %d years old.", DE: "Mein Name ist %s und ich bin %d Jahre alt.", }.Get func main() { fmt.Printf("Monday in EN: %s\n", Monday(EN)) fmt.Printf("Monday in DE: %s\n", Monday(DE)) fmt.Printf("Monday in HU: %s (empty)\n", Monday(HU)) fmt.Printf("Monday in GR: %s (missing, defaults to EN)\n", Monday(GR)) fmt.Println(Introduce(EN, "Bob", 22)) fmt.Println(Introduce(DE, "Alice", 12)) }
Output: Monday in EN: Monday Monday in DE: Montag Monday in HU: (empty) Monday in GR: Monday (missing, defaults to EN) My name is Bob, and I'm 22 years old. Mein Name ist Alice und ich bin 12 Jahre alt.
Index ¶
Examples ¶
Constants ¶
const Empty = "\xff"
Empty is a string which translates into the empty string "". Needed because empty strings in Dict denote missing translations.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Dict ¶
type Dict []string
Dict describes a dictionary, it holds translations of a phrase or sentence.
Keyed composite literals should be used always to create instances, where keys (indices) are the locales.
Empty string elements "" denote missing translations for the locale denoted by the index. If you want the translation to be the empty string, you must use the Empty constant as the value.
func (Dict) Get ¶
Get returns the translation for the given locale. If no translation exists for the given locale, translation for the default locale (which is 0) is returned.
If arguments are provided, the translation is treated as a format string, and fmt.Sprintf() is called to generate the result.
If the translation is the Empty constant, the empty string is returned without calling fmt.Sprintf() even if arguments are provided.
type Translator ¶
Translator is the type of the Dict.Get method.