Localization (i18n)

  1. Translating a Def
  2. Fallback chain
  3. Translating a registered type
  4. Available locales

enumx translates enum values without a third-party i18n library. It ships 100+ ISO 639-1 locale constants as a typed Locale string, so a misspelled locale is a compile error rather than a silent miss.

Translating a Def

status := enumx.New("pending", "active", "blocked")

// A whole locale at once
status.AddTranslation(enumx.UZ, map[string]string{
    "pending": "Kutilmoqda",
    "active":  "Faol",
    "blocked": "Bloklangan",
})

// Or one at a time, chainable
status.SetTranslation(enumx.EN, "pending", "Pending").
    SetTranslation(enumx.EN, "active", "Active")

status.Translate("pending", enumx.UZ) // "Kutilmoqda"

Both methods ignore values that are not members of the enum, so a typo cannot introduce a translation for a value that does not exist.

Any locale is accepted, not just the predefined constants:

status.AddTranslation(enumx.Locale("kk"), map[string]string{"pending": "Күтілуде"})

MutableDef has the identical API and takes its lock on every call.

Fallback chain

A lookup is resolved in this order:

  1. the exact locale — pt-BR
  2. the base locale, with region and script subtags stripped — pt
  3. the fallback locale, en by default
  4. the raw value
status.Translate("pending", enumx.Locale("uz-UZ")) // "Kutilmoqda" — falls back to uz
status.Translate("pending", enumx.RU)             // "Pending"    — falls back to en

Change or disable the fallback globally:

enumx.SetFallbackLocale(enumx.UZ) // prefer Uzbek when a locale is missing
enumx.SetFallbackLocale("")       // no fallback: misses return the raw value

Translating a registered type

For types registered with enumx.Register, the same rules apply through the package-level registry:

enumx.RegisterLocales(StatusPending, map[string]string{
    "en": "Pending",
    "uz": "Kutilmoqda",
})

enumx.LocaleLabel(StatusPending, "uz")     // "Kutilmoqda"
enumx.LocaleLabel(StatusPending, "uz-UZ")  // "Kutilmoqda"
enumx.LocaleLabel(StatusPending, "ru")     // "Pending" — falls back to en

Repeated calls for the same value merge into the labels already registered, so you can add a locale later without restating the others. Registration is safe to call from several goroutines.

If you use the Enum[T] wrapper, Label is the method form:

user.Status.Label("uz") // "Kutilmoqda"

Available locales

enumx predefines constants for the 100+ most widely spoken languages — EN, ZH, HI, ES, FR, AR, RU, PT, UZ, KK, TR, JA, KO, DE, … — as well as three-letter codes such as YUE, BHO, and HAK. See locale.go for the full list.