countrycodes

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 12, 2025 License: MIT Imports: 0 Imported by: 0

README

countrycodes

Ultra-fast, zero-allocation, zero-dependency ISO 3166-1 country code library for Go. All lookups are compile-time optimized with O(1) complexity and absolutely no memory allocations.

Features

  • Zero dependencies - Absolutely no external packages in go.mod
  • Zero allocations - All operations are allocation-free
  • Blazing fast - ~0.3-8 nanoseconds per lookup
  • Compile-time optimized - Uses switch statements and lookup arrays
  • Type safe - All conversions verified at compile time
  • Case-insensitive - All lookups accept any case and return proper ISO format
  • Name-based lookups - Get country codes from country names
  • Complete ISO 3166-1 coverage - All 249 countries included
  • Regional data - UN M.49 regions and sub-regions included
  • Country code constants - Type-safe constants for all alpha-2 and alpha-3 codes

Installation

go get github.com/flaticols/countrycodes

Usage

package main

import (
    "fmt"
    "github.com/flaticols/countrycodes"
)

func main() {
    // Convert between alpha-2 and alpha-3 codes (case-insensitive)
    alpha3, ok := countrycodes.Alpha2ToAlpha3("fr")  // lowercase works!
    fmt.Println(alpha3, ok) // FRA true

    alpha2, ok := countrycodes.Alpha3ToAlpha2("deu")  // lowercase works!
    fmt.Println(alpha2, ok) // DE true

    // Convert to/from UN M.49 numeric codes (string)
    number, ok := countrycodes.Alpha2ToNumber("IT")
    fmt.Println(number, ok) // 380 true

    alpha2, ok = countrycodes.NumberToAlpha2("528")
    fmt.Println(alpha2, ok) // NL true

    // Convert using integer country codes (faster!)
    numInt, ok := countrycodes.Alpha2ToNumberInt("ES")
    fmt.Println(numInt, ok) // 724 true

    alpha2, ok = countrycodes.NumberIntToAlpha2(56)
    fmt.Println(alpha2, ok) // BE true

    // Get country names (case-insensitive)
    name, ok := countrycodes.Alpha2ToName("pl")  // lowercase works!
    fmt.Println(name, ok) // Poland true

    // Get country codes from names (case-insensitive)
    alpha2, ok = countrycodes.NameToAlpha2("netherlands, kingdom of the")
    fmt.Println(alpha2, ok) // NL true

    alpha3, ok = countrycodes.NameToAlpha3("ITALY")  // uppercase works!
    fmt.Println(alpha3, ok) // ITA true

    num, ok := countrycodes.NameToNumber("Germany")
    fmt.Println(num, ok) // 276 true

    // Get complete country information (case-insensitive)
    country, ok := countrycodes.GetByAlpha2("se")  // lowercase works!
    fmt.Println(country.Name)          // Sweden
    fmt.Println(country.Alpha3)        // SWE
    fmt.Println(country.CountryCode)   // 752
    fmt.Println(country.ISO31662)      // ISO 3166-2:SE
    fmt.Println(country.Region)        // Europe
    fmt.Println(country.SubRegion)     // Northern Europe

    // Get country by name (case-insensitive)
    country, ok = countrycodes.GetByName("switzerland")
    fmt.Println(country.Alpha2)        // CH
    fmt.Println(country.Alpha3)        // CHE

    // Country with intermediate region
    country, ok = countrycodes.GetByAlpha2("MX")
    fmt.Println(country.IntermediateRegion) // Central America

    // Validate codes (case-insensitive)
    fmt.Println(countrycodes.IsValidAlpha2("dk"))  // true (lowercase works!)
    fmt.Println(countrycodes.IsValidAlpha3("xxx")) // false
    fmt.Println(countrycodes.IsValidName("spain")) // true (case-insensitive!)

    // Use type-safe constants with country names for alpha-2 codes
    name, ok = countrycodes.Alpha2ToName(countrycodes.Netherlands)
    fmt.Println(name, ok) // Netherlands, Kingdom of the true

    alpha3, ok = countrycodes.Alpha2ToAlpha3(countrycodes.France)
    fmt.Println(alpha3, ok) // FRA true

    // Use type-safe constants with country names for alpha-3 codes (in subpackage)
    import "github.com/flaticols/countrycodes/alpha3"
    
    alpha2, ok = countrycodes.Alpha3ToAlpha2(alpha3.Germany)
    fmt.Println(alpha2, ok) // DE true

    name, ok = countrycodes.Alpha3ToName(alpha3.Italy)
    fmt.Println(name, ok) // Italy true
}

Performance

Benchmark results on Apple M1 Pro:

BenchmarkAlpha2ToNumberInt-10           131171708                9.192 ns/op           0 B/op          0 allocs/op
BenchmarkNumberIntToAlpha2-10           1000000000               0.3152 ns/op          0 B/op          0 allocs/op
BenchmarkGetByNumberInt-10              158944388                7.537 ns/op           0 B/op          0 allocs/op
BenchmarkIsValidNumberInt-10            1000000000               0.3146 ns/op          0 B/op          0 allocs/op
BenchmarkNumberToAlpha2_String-10       100000000               15.17 ns/op            0 B/op          0 allocs/op
BenchmarkNumberToAlpha2_Int-10          1000000000               0.3128 ns/op          0 B/op          0 allocs/op
BenchmarkGetByNumber_String-10          153581832                7.538 ns/op           0 B/op          0 allocs/op
BenchmarkGetByNumber_Int-10             161488239                7.470 ns/op           0 B/op          0 allocs/op
BenchmarkAlpha2ToAlpha3-10              174179803                6.867 ns/op           0 B/op          0 allocs/op
BenchmarkAlpha3ToAlpha2-10              189879138                6.270 ns/op           0 B/op          0 allocs/op
BenchmarkNumberToAlpha2-10              87254749                13.79 ns/op            0 B/op          0 allocs/op
BenchmarkGetByAlpha2-10                 167205633                7.179 ns/op           0 B/op          0 allocs/op
BenchmarkIsValidAlpha2-10               174320918                6.855 ns/op           0 B/op          0 allocs/op
BenchmarkAlpha2ToAlpha3_Allocs-10       174757227                6.857 ns/op           0 B/op          0 allocs/op
BenchmarkGetByAlpha2_Allocs-10          84646881                14.07 ns/op            0 B/op          0 allocs/op
BenchmarkNameToAlpha2-10                23234931                51.57 ns/op            0 B/op          0 allocs/op
BenchmarkNameToAlpha3-10                23277316                52.61 ns/op            0 B/op          0 allocs/op
BenchmarkNameToNumberInt-10             23410104                51.28 ns/op            0 B/op          0 allocs/op
BenchmarkGetByName-10                   14574456                81.51 ns/op            0 B/op          0 allocs/op
BenchmarkIsValidName-10                 23539681                50.89 ns/op            0 B/op          0 allocs/op
BenchmarkNameToAlpha2_Allocs-10         23208399                51.67 ns/op            0 B/op          0 allocs/op
BenchmarkGetByName_Allocs-10            14151721                84.46 ns/op            0 B/op          0 allocs/op

Architecture

This library maintains zero dependencies through a clever architecture:

  • Main module (github.com/flaticols/countrycodes) - Zero dependencies, contains only the library code
  • Data files (data/*.json) - Pre-committed JSON files with country data
  • Code generator (cmd/generator) - Generates optimized Go code from JSON files
  • Data scrubber (cmd/scrubber) - Separate module for updating data (with its own dependencies)

Development

# Show all available commands
make help

# Generate optimized code from data/*.json files
make generate

# Run tests
make test

# Run benchmarks
make bench

# Update country data from Wikipedia/UN (requires network)
make scrub

# Update data and regenerate code
make update

# Clean all generated files
make clean
Updating Country Data

The country data is stored in JSON files under the data/ directory. To update it:

# This fetches latest data from Wikipedia and UN sources
make scrub

# Then regenerate the Go code
make generate

Note: The scrubber tool is in a separate module (cmd/scrubber) to keep the main library dependency-free.

Data Sources

Country data is sourced from:

The data is pre-committed to ensure reproducible builds and zero runtime dependencies.

License

MIT

Documentation

Overview

Package countrycodes provides ultra-fast, zero-allocation ISO 3166-1 country code conversions. All lookups are O(1) using compile-time optimized switch statements.

Index

Constants

View Source
const (
	// Andorra - Andorra
	Andorra = "AD"
	// UnitedArabEmirates - United Arab Emirates
	UnitedArabEmirates = "AE"
	// Afghanistan - Afghanistan
	Afghanistan = "AF"
	// AntiguaBarbuda - Antigua and Barbuda
	AntiguaBarbuda = "AG"
	// Anguilla - Anguilla
	Anguilla = "AI"
	// Albania - Albania
	Albania = "AL"
	// Armenia - Armenia
	Armenia = "AM"
	// Angola - Angola
	Angola = "AO"
	// Antarctica - Antarctica
	Antarctica = "AQ"
	// Argentina - Argentina
	Argentina = "AR"
	// AmericanSamoa - American Samoa
	AmericanSamoa = "AS"
	// Austria - Austria
	Austria = "AT"
	// Australia - Australia
	Australia = "AU"
	// Aruba - Aruba
	Aruba = "AW"
	// AlandIslands - Åland Islands
	AlandIslands = "AX"
	// Azerbaijan - Azerbaijan
	Azerbaijan = "AZ"
	// BosniaHerzegovina - Bosnia and Herzegovina
	BosniaHerzegovina = "BA"
	// Barbados - Barbados
	Barbados = "BB"
	// Bangladesh - Bangladesh
	Bangladesh = "BD"
	// Belgium - Belgium
	Belgium = "BE"
	// BurkinaFaso - Burkina Faso
	BurkinaFaso = "BF"
	// Bulgaria - Bulgaria
	Bulgaria = "BG"
	// Bahrain - Bahrain
	Bahrain = "BH"
	// Burundi - Burundi
	Burundi = "BI"
	// Benin - Benin
	Benin = "BJ"
	// SaintBarthelemy - Saint Barthélemy
	SaintBarthelemy = "BL"
	// Bermuda - Bermuda
	Bermuda = "BM"
	// Brunei - Brunei Darussalam
	Brunei = "BN"
	// Bolivia - Bolivia, Plurinational State of
	Bolivia = "BO"
	// CaribbeanNetherlands - Bonaire, Sint Eustatius and Saba
	CaribbeanNetherlands = "BQ"
	// Brazil - Brazil
	Brazil = "BR"
	// Bahamas - Bahamas
	Bahamas = "BS"
	// Bhutan - Bhutan
	Bhutan = "BT"
	// BouvetIsland - Bouvet Island
	BouvetIsland = "BV"
	// Botswana - Botswana
	Botswana = "BW"
	// Belarus - Belarus
	Belarus = "BY"
	// Belize - Belize
	Belize = "BZ"
	// Canada - Canada
	Canada = "CA"
	// CocosIslands - Cocos (Keeling) Islands
	CocosIslands = "CC"
	// CongoDRC - Congo, Democratic Republic of the
	CongoDRC = "CD"
	// CentralAfricanRepublic - Central African Republic
	CentralAfricanRepublic = "CF"
	// CongoBrazzaville - Congo
	CongoBrazzaville = "CG"
	// Switzerland - Switzerland
	Switzerland = "CH"
	// CoteDIvoire - Côte d'Ivoire
	CoteDIvoire = "CI"
	// CookIslands - Cook Islands
	CookIslands = "CK"
	// Chile - Chile
	Chile = "CL"
	// Cameroon - Cameroon
	Cameroon = "CM"
	// China - China
	China = "CN"
	// Colombia - Colombia
	Colombia = "CO"
	// CostaRica - Costa Rica
	CostaRica = "CR"
	// Cuba - Cuba
	Cuba = "CU"
	// CapeVerde - Cabo Verde
	CapeVerde = "CV"
	// Curacao - Curaçao
	Curacao = "CW"
	// ChristmasIsland - Christmas Island
	ChristmasIsland = "CX"
	// Cyprus - Cyprus
	Cyprus = "CY"
	// CzechRepublic - Czechia
	CzechRepublic = "CZ"
	// Germany - Germany
	Germany = "DE"
	// Djibouti - Djibouti
	Djibouti = "DJ"
	// Denmark - Denmark
	Denmark = "DK"
	// Dominica - Dominica
	Dominica = "DM"
	// DominicanRepublic - Dominican Republic
	DominicanRepublic = "DO"
	// Algeria - Algeria
	Algeria = "DZ"
	// Ecuador - Ecuador
	Ecuador = "EC"
	// Estonia - Estonia
	Estonia = "EE"
	// Egypt - Egypt
	Egypt = "EG"
	// WesternSahara - Western Sahara
	WesternSahara = "EH"
	// Eritrea - Eritrea
	Eritrea = "ER"
	// Spain - Spain
	Spain = "ES"
	// Ethiopia - Ethiopia
	Ethiopia = "ET"
	// Finland - Finland
	Finland = "FI"
	// Fiji - Fiji
	Fiji = "FJ"
	// FalklandIslands - Falkland Islands (Malvinas)
	FalklandIslands = "FK"
	// Micronesia - Micronesia, Federated States of
	Micronesia = "FM"
	// FaroeIslands - Faroe Islands
	FaroeIslands = "FO"
	// France - France
	France = "FR"
	// Gabon - Gabon
	Gabon = "GA"
	// UnitedKingdom - United Kingdom of Great Britain and Northern Ireland
	UnitedKingdom = "GB"
	// Grenada - Grenada
	Grenada = "GD"
	// Georgia - Georgia
	Georgia = "GE"
	// FrenchGuiana - French Guiana
	FrenchGuiana = "GF"
	// Guernsey - Guernsey
	Guernsey = "GG"
	// Ghana - Ghana
	Ghana = "GH"
	// Gibraltar - Gibraltar
	Gibraltar = "GI"
	// Greenland - Greenland
	Greenland = "GL"
	// Gambia - Gambia
	Gambia = "GM"
	// Guinea - Guinea
	Guinea = "GN"
	// Guadeloupe - Guadeloupe
	Guadeloupe = "GP"
	// EquatorialGuinea - Equatorial Guinea
	EquatorialGuinea = "GQ"
	// Greece - Greece
	Greece = "GR"
	// SouthGeorgiaAndSouthSandwichIslands - South Georgia and the South Sandwich Islands
	SouthGeorgiaAndSouthSandwichIslands = "GS"
	// Guatemala - Guatemala
	Guatemala = "GT"
	// Guam - Guam
	Guam = "GU"
	// GuineaBissau - Guinea-Bissau
	GuineaBissau = "GW"
	// Guyana - Guyana
	Guyana = "GY"
	// HongKong - Hong Kong
	HongKong = "HK"
	// HeardAndMcDonaldIslands - Heard Island and McDonald Islands
	HeardAndMcDonaldIslands = "HM"
	// Honduras - Honduras
	Honduras = "HN"
	// Croatia - Croatia
	Croatia = "HR"
	// Haiti - Haiti
	Haiti = "HT"
	// Hungary - Hungary
	Hungary = "HU"
	// Indonesia - Indonesia
	Indonesia = "ID"
	// Ireland - Ireland
	Ireland = "IE"
	// Israel - Israel
	Israel = "IL"
	// IsleMan - Isle of Man
	IsleMan = "IM"
	// India - India
	India = "IN"
	// BritishIndianOceanTerritory - British Indian Ocean Territory
	BritishIndianOceanTerritory = "IO"
	// Iraq - Iraq
	Iraq = "IQ"
	// Iran - Iran, Islamic Republic of
	Iran = "IR"
	// Iceland - Iceland
	Iceland = "IS"
	// Italy - Italy
	Italy = "IT"
	// Jersey - Jersey
	Jersey = "JE"
	// Jamaica - Jamaica
	Jamaica = "JM"
	// Jordan - Jordan
	Jordan = "JO"
	// Japan - Japan
	Japan = "JP"
	// Kenya - Kenya
	Kenya = "KE"
	// Kyrgyzstan - Kyrgyzstan
	Kyrgyzstan = "KG"
	// Cambodia - Cambodia
	Cambodia = "KH"
	// Kiribati - Kiribati
	Kiribati = "KI"
	// Comoros - Comoros
	Comoros = "KM"
	// SaintKittsNevis - Saint Kitts and Nevis
	SaintKittsNevis = "KN"
	// NorthKorea - Korea, Democratic People's Republic of
	NorthKorea = "KP"
	// SouthKorea - Korea, Republic of
	SouthKorea = "KR"
	// Kuwait - Kuwait
	Kuwait = "KW"
	// CaymanIslands - Cayman Islands
	CaymanIslands = "KY"
	// Kazakhstan - Kazakhstan
	Kazakhstan = "KZ"
	// Laos - Lao People's Democratic Republic
	Laos = "LA"
	// Lebanon - Lebanon
	Lebanon = "LB"
	// SaintLucia - Saint Lucia
	SaintLucia = "LC"
	// Liechtenstein - Liechtenstein
	Liechtenstein = "LI"
	// SriLanka - Sri Lanka
	SriLanka = "LK"
	// Liberia - Liberia
	Liberia = "LR"
	// Lesotho - Lesotho
	Lesotho = "LS"
	// Lithuania - Lithuania
	Lithuania = "LT"
	// Luxembourg - Luxembourg
	Luxembourg = "LU"
	// Latvia - Latvia
	Latvia = "LV"
	// Libya - Libya
	Libya = "LY"
	// Morocco - Morocco
	Morocco = "MA"
	// Monaco - Monaco
	Monaco = "MC"
	// Moldova - Moldova, Republic of
	Moldova = "MD"
	// Montenegro - Montenegro
	Montenegro = "ME"
	// SaintMartinFrench - Saint Martin (French part)
	SaintMartinFrench = "MF"
	// Madagascar - Madagascar
	Madagascar = "MG"
	// MarshallIslands - Marshall Islands
	MarshallIslands = "MH"
	// NorthMacedonia - North Macedonia
	NorthMacedonia = "MK"
	// Mali - Mali
	Mali = "ML"
	// Myanmar - Myanmar
	Myanmar = "MM"
	// Mongolia - Mongolia
	Mongolia = "MN"
	// Macau - Macao
	Macau = "MO"
	// NorthernMarianaIslands - Northern Mariana Islands
	NorthernMarianaIslands = "MP"
	// Martinique - Martinique
	Martinique = "MQ"
	// Mauritania - Mauritania
	Mauritania = "MR"
	// Montserrat - Montserrat
	Montserrat = "MS"
	// Malta - Malta
	Malta = "MT"
	// Mauritius - Mauritius
	Mauritius = "MU"
	// Maldives - Maldives
	Maldives = "MV"
	// Malawi - Malawi
	Malawi = "MW"
	// Mexico - Mexico
	Mexico = "MX"
	// Malaysia - Malaysia
	Malaysia = "MY"
	// Mozambique - Mozambique
	Mozambique = "MZ"
	// Namibia - Namibia
	Namibia = "NA"
	// NewCaledonia - New Caledonia
	NewCaledonia = "NC"
	// Niger - Niger
	Niger = "NE"
	// NorfolkIsland - Norfolk Island
	NorfolkIsland = "NF"
	// Nigeria - Nigeria
	Nigeria = "NG"
	// Nicaragua - Nicaragua
	Nicaragua = "NI"
	// Netherlands - Netherlands, Kingdom of the
	Netherlands = "NL"
	// Norway - Norway
	Norway = "NO"
	// Nepal - Nepal
	Nepal = "NP"
	// Nauru - Nauru
	Nauru = "NR"
	// Niue - Niue
	Niue = "NU"
	// NewZealand - New Zealand
	NewZealand = "NZ"
	// Oman - Oman
	Oman = "OM"
	// Panama - Panama
	Panama = "PA"
	// Peru - Peru
	Peru = "PE"
	// FrenchPolynesia - French Polynesia
	FrenchPolynesia = "PF"
	// PapuaNewGuinea - Papua New Guinea
	PapuaNewGuinea = "PG"
	// Philippines - Philippines
	Philippines = "PH"
	// Pakistan - Pakistan
	Pakistan = "PK"
	// Poland - Poland
	Poland = "PL"
	// SaintPierreAndMiquelon - Saint Pierre and Miquelon
	SaintPierreAndMiquelon = "PM"
	// Pitcairn - Pitcairn
	Pitcairn = "PN"
	// PuertoRico - Puerto Rico
	PuertoRico = "PR"
	// Palestine - Palestine, State of
	Palestine = "PS"
	// Portugal - Portugal
	Portugal = "PT"
	// Palau - Palau
	Palau = "PW"
	// Paraguay - Paraguay
	Paraguay = "PY"
	// Qatar - Qatar
	Qatar = "QA"
	// Reunion - Réunion
	Reunion = "RE"
	// Romania - Romania
	Romania = "RO"
	// Serbia - Serbia
	Serbia = "RS"
	// Russia - Russian Federation
	Russia = "RU"
	// Rwanda - Rwanda
	Rwanda = "RW"
	// SaudiArabia - Saudi Arabia
	SaudiArabia = "SA"
	// SolomonIslands - Solomon Islands
	SolomonIslands = "SB"
	// Seychelles - Seychelles
	Seychelles = "SC"
	// Sudan - Sudan
	Sudan = "SD"
	// Sweden - Sweden
	Sweden = "SE"
	// Singapore - Singapore
	Singapore = "SG"
	// SaintHelena - Saint Helena, Ascension and Tristan da Cunha
	SaintHelena = "SH"
	// Slovenia - Slovenia
	Slovenia = "SI"
	// SvalbardAndJanMayen - Svalbard and Jan Mayen
	SvalbardAndJanMayen = "SJ"
	// Slovakia - Slovakia
	Slovakia = "SK"
	// SierraLeone - Sierra Leone
	SierraLeone = "SL"
	// SanMarino - San Marino
	SanMarino = "SM"
	// Senegal - Senegal
	Senegal = "SN"
	// Somalia - Somalia
	Somalia = "SO"
	// Suriname - Suriname
	Suriname = "SR"
	// SouthSudan - South Sudan
	SouthSudan = "SS"
	// SaoTomePrincipe - Sao Tome and Principe
	SaoTomePrincipe = "ST"
	// ElSalvador - El Salvador
	ElSalvador = "SV"
	// SintMaartenDutch - Sint Maarten (Dutch part)
	SintMaartenDutch = "SX"
	// Syria - Syrian Arab Republic
	Syria = "SY"
	// Eswatini - Eswatini
	Eswatini = "SZ"
	// TurksAndCaicosIslands - Turks and Caicos Islands
	TurksAndCaicosIslands = "TC"
	// Chad - Chad
	Chad = "TD"
	// FrenchSouthernTerritories - French Southern Territories
	FrenchSouthernTerritories = "TF"
	// Togo - Togo
	Togo = "TG"
	// Thailand - Thailand
	Thailand = "TH"
	// Tajikistan - Tajikistan
	Tajikistan = "TJ"
	// Tokelau - Tokelau
	Tokelau = "TK"
	// TimorLeste - Timor-Leste
	TimorLeste = "TL"
	// Turkmenistan - Turkmenistan
	Turkmenistan = "TM"
	// Tunisia - Tunisia
	Tunisia = "TN"
	// Tonga - Tonga
	Tonga = "TO"
	// Turkiye - Türkiye
	Turkiye = "TR"
	// TrinidadTobago - Trinidad and Tobago
	TrinidadTobago = "TT"
	// Tuvalu - Tuvalu
	Tuvalu = "TV"
	// Taiwan - Taiwan, Province of China
	Taiwan = "TW"
	// Tanzania - Tanzania, United Republic of
	Tanzania = "TZ"
	// Ukraine - Ukraine
	Ukraine = "UA"
	// Uganda - Uganda
	Uganda = "UG"
	// USMinorOutlyingIslands - United States Minor Outlying Islands
	USMinorOutlyingIslands = "UM"
	// UnitedStates - United States of America
	UnitedStates = "US"
	// Uruguay - Uruguay
	Uruguay = "UY"
	// Uzbekistan - Uzbekistan
	Uzbekistan = "UZ"
	// VaticanCity - Holy See
	VaticanCity = "VA"
	// SaintVincentGrenadines - Saint Vincent and the Grenadines
	SaintVincentGrenadines = "VC"
	// Venezuela - Venezuela, Bolivarian Republic of
	Venezuela = "VE"
	// BritishVirginIslands - Virgin Islands (British)
	BritishVirginIslands = "VG"
	// USVirginIslands - Virgin Islands (U.S.)
	USVirginIslands = "VI"
	// Vietnam - Viet Nam
	Vietnam = "VN"
	// Vanuatu - Vanuatu
	Vanuatu = "VU"
	// WallisAndFutuna - Wallis and Futuna
	WallisAndFutuna = "WF"
	// Samoa - Samoa
	Samoa = "WS"
	// Yemen - Yemen
	Yemen = "YE"
	// Mayotte - Mayotte
	Mayotte = "YT"
	// SouthAfrica - South Africa
	SouthAfrica = "ZA"
	// Zambia - Zambia
	Zambia = "ZM"
	// Zimbabwe - Zimbabwe
	Zimbabwe = "ZW"
)

ISO 3166-1 alpha-2 country code constants. These constants provide compile-time type safety and IDE autocomplete support.

Usage:

name, _ := Alpha2ToName(countrycodes.Netherlands)
alpha3, _ := Alpha2ToAlpha3(countrycodes.France)

Variables

This section is empty.

Functions

func Alpha2ToAlpha3

func Alpha2ToAlpha3(code string) (string, bool)

Alpha2ToAlpha3 converts an ISO 3166-1 alpha-2 code to its corresponding alpha-3 code.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive matching. The input is case-insensitive.

Parameters:

  • code: ISO 3166-1 alpha-2 code (e.g., "FR", "de", "IT", "es")

Returns:

  • string: The corresponding alpha-3 code in uppercase if found
  • bool: true if the conversion succeeded, false if the input code is invalid

Example:

if alpha3, ok := Alpha2ToAlpha3("fr"); ok {
    fmt.Println(alpha3) // Output: FRA
}

func Alpha2ToName

func Alpha2ToName(code string) (string, bool)

Alpha2ToName retrieves the country name for an ISO 3166-1 alpha-2 code.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive matching. Use this for displaying human-readable country names. The input is case-insensitive.

Parameters:

  • code: ISO 3166-1 alpha-2 code (e.g., "FR", "de", "IT", "es")

Returns:

  • string: The official English short name from ISO 3166-1
  • bool: true if the code exists, false otherwise

Example:

if name, ok := Alpha2ToName("fr"); ok {
    fmt.Println(name) // Output: France
}

Note: Country names follow the official ISO 3166-1 English short names.

func Alpha2ToNumber

func Alpha2ToNumber(code string) (string, bool)

Alpha2ToNumber converts an ISO 3166-1 alpha-2 code to its UN M.49 numeric code.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive matching. The numeric code is returned as a string with leading zeros. The input is case-insensitive.

Parameters:

  • code: ISO 3166-1 alpha-2 code (e.g., "GB", "nl", "PL", "se")

Returns:

  • string: The UN M.49 numeric code with leading zeros (e.g., "826", "528")
  • bool: true if the conversion succeeded, false if the input code is invalid

Example:

if num, ok := Alpha2ToNumber("gb"); ok {
    fmt.Println(num) // Output: 826
}

Note: For integer results, use Alpha2ToNumberInt instead.

func Alpha2ToNumberInt

func Alpha2ToNumberInt(code string) (int, bool)

Alpha2ToNumberInt converts an ISO 3166-1 alpha-2 code to its UN M.49 numeric code as an integer.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive matching. This is the fastest way to get a numeric code as an integer. The input is case-insensitive.

Parameters:

  • code: ISO 3166-1 alpha-2 code (e.g., "US", "us", "GB", "gb")

Returns:

  • int: The UN M.49 numeric code as integer (e.g., 840 for "US")
  • bool: true if the conversion succeeded, false if the input code is invalid

Example:

if num, ok := Alpha2ToNumberInt("us"); ok {
    fmt.Printf("Numeric code: %d\n", num) // Output: Numeric code: 840
}

func Alpha3ToAlpha2

func Alpha3ToAlpha2(code string) (string, bool)

Alpha3ToAlpha2 converts an ISO 3166-1 alpha-3 code to its corresponding alpha-2 code.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive matching. The input is case-insensitive.

Parameters:

  • code: ISO 3166-1 alpha-3 code (e.g., "DEU", "fra", "ITA", "esp")

Returns:

  • string: The corresponding alpha-2 code in uppercase if found
  • bool: true if the conversion succeeded, false if the input code is invalid

Example:

if alpha2, ok := Alpha3ToAlpha2("deu"); ok {
    fmt.Println(alpha2) // Output: DE
}

func Alpha3ToName

func Alpha3ToName(code string) (string, bool)

Alpha3ToName retrieves the country name for an ISO 3166-1 alpha-3 code.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive matching. Use this for displaying human-readable country names. The input is case-insensitive.

Parameters:

  • code: ISO 3166-1 alpha-3 code (e.g., "DEU", "ita", "NLD", "bel")

Returns:

  • string: The official English short name from ISO 3166-1
  • bool: true if the code exists, false otherwise

Example:

if name, ok := Alpha3ToName("deu"); ok {
    fmt.Println(name) // Output: Germany
}

Note: Country names follow the official ISO 3166-1 English short names.

func Alpha3ToNumber

func Alpha3ToNumber(code string) (string, bool)

Alpha3ToNumber converts an ISO 3166-1 alpha-3 code to its UN M.49 numeric code.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive matching. The numeric code is returned as a string with leading zeros. The input is case-insensitive.

Parameters:

  • code: ISO 3166-1 alpha-3 code (e.g., "NLD", "bel", "CHE", "aut")

Returns:

  • string: The UN M.49 numeric code with leading zeros (e.g., "528", "056")
  • bool: true if the conversion succeeded, false if the input code is invalid

Example:

if num, ok := Alpha3ToNumber("nld"); ok {
    fmt.Println(num) // Output: 528
}

Note: For integer results, use Alpha3ToNumberInt instead.

func Alpha3ToNumberInt

func Alpha3ToNumberInt(code string) (int, bool)

Alpha3ToNumberInt converts an ISO 3166-1 alpha-3 code to its UN M.49 numeric code as an integer.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive matching. This is the fastest way to get a numeric code as an integer. The input is case-insensitive.

Parameters:

  • code: ISO 3166-1 alpha-3 code (e.g., "USA", "usa", "GBR", "gbr")

Returns:

  • int: The UN M.49 numeric code as integer (e.g., 840 for "USA")
  • bool: true if the conversion succeeded, false if the input code is invalid

Example:

if num, ok := Alpha3ToNumberInt("usa"); ok {
    fmt.Printf("Numeric code: %d\n", num) // Output: Numeric code: 840
}

func IsValidAlpha2

func IsValidAlpha2(code string) bool

IsValidAlpha2 validates whether the given string is a valid ISO 3166-1 alpha-2 code.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive validation. Use this to validate user input before conversions. The validation is case-insensitive.

Parameters:

  • code: String to validate as an ISO 3166-1 alpha-2 code (e.g., "FR", "de")

Returns:

  • bool: true if the code is a valid ISO 3166-1 alpha-2 code, false otherwise

Example:

if IsValidAlpha2("fr") {
    // Process valid country code
    alpha3, _ := Alpha2ToAlpha3("fr")
    fmt.Println(alpha3)
}

func IsValidAlpha3

func IsValidAlpha3(code string) bool

IsValidAlpha3 validates whether the given string is a valid ISO 3166-1 alpha-3 code.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive validation. Use this to validate user input before conversions. The validation is case-insensitive.

Parameters:

  • code: String to validate as an ISO 3166-1 alpha-3 code (e.g., "ITA", "esp")

Returns:

  • bool: true if the code is a valid ISO 3166-1 alpha-3 code, false otherwise

Example:

if IsValidAlpha3("ita") {
    // Process valid country code
    alpha2, _ := Alpha3ToAlpha2("ita")
    fmt.Println(alpha2)
}

func IsValidName

func IsValidName(name string) bool

IsValidName validates whether the given string is a valid country name.

This function uses a hash table with linear probing for O(1) average-case lookups with zero allocations. The validation is case-insensitive.

Parameters:

  • name: String to validate as a country name (e.g., "Germany", "france")

Returns:

  • bool: true if the name is a valid country name, false otherwise

Example:

if IsValidName("germany") {
    // Process valid country name
    alpha2, _ := NameToAlpha2("germany")
    fmt.Println(alpha2)
}

func IsValidNumber

func IsValidNumber(code string) bool

IsValidNumber validates whether the given string is a valid UN M.49 numeric code.

This function performs an O(1) map lookup with zero memory allocations. The function accepts numeric codes with leading zeros.

Parameters:

  • code: String to validate as a UN M.49 numeric code (e.g., "276", "380")

Returns:

  • bool: true if the code is a valid UN M.49 numeric code, false otherwise

Example:

if IsValidNumber("276") {
    // Process valid numeric code
    alpha2, _ := NumberToAlpha2("276")
    fmt.Println(alpha2)
}

Note: For integer validation, use IsValidNumberInt for better performance.

func IsValidNumberInt

func IsValidNumberInt(code int) bool

IsValidNumberInt checks if the given integer is a valid UN M.49 numeric code.

This function uses direct array bounds checking for O(1) performance.

Parameters:

  • code: Integer to validate as UN M.49 numeric code

Returns:

  • bool: true if the code is a valid UN M.49 numeric code, false otherwise

Example:

if IsValidNumberInt(840) {
    fmt.Println("Valid UN M.49 code")
}

Performance: Sub-nanosecond validation with zero allocations.

func NameToAlpha2

func NameToAlpha2(name string) (string, bool)

NameToAlpha2 retrieves the ISO 3166-1 alpha-2 code for a country name.

This function uses a hash table with linear probing for O(1) average-case lookups with zero allocations. The lookup is case-insensitive.

Parameters:

  • name: Country name (e.g., "Germany", "FRANCE", "italy")

Returns:

  • string: The corresponding alpha-2 code in uppercase if found
  • bool: true if the name exists, false otherwise

Example:

if alpha2, ok := NameToAlpha2("germany"); ok {
    fmt.Println(alpha2) // Output: DE
}

func NameToAlpha3

func NameToAlpha3(name string) (string, bool)

NameToAlpha3 retrieves the ISO 3166-1 alpha-3 code for a country name.

This function uses a hash table with linear probing for O(1) average-case lookups with zero allocations. The lookup is case-insensitive.

Parameters:

  • name: Country name (e.g., "Netherlands", "BELGIUM", "spain")

Returns:

  • string: The corresponding alpha-3 code in uppercase if found
  • bool: true if the name exists, false otherwise

Example:

if alpha3, ok := NameToAlpha3("netherlands"); ok {
    fmt.Println(alpha3) // Output: NLD
}

func NameToNumber

func NameToNumber(name string) (string, bool)

NameToNumber retrieves the UN M.49 numeric code for a country name.

This function uses a hash table with linear probing for O(1) average-case lookups with zero allocations. The lookup is case-insensitive.

Parameters:

  • name: Country name (e.g., "France", "ITALY", "poland")

Returns:

  • string: The UN M.49 numeric code with leading zeros if found
  • bool: true if the name exists, false otherwise

Example:

if num, ok := NameToNumber("france"); ok {
    fmt.Println(num) // Output: 250
}

Note: For integer results, use NameToNumberInt for better performance.

func NameToNumberInt

func NameToNumberInt(name string) (int, bool)

NameToNumberInt retrieves the UN M.49 numeric code for a country name as an integer.

This function uses a hash table with linear probing for O(1) average-case lookups with zero allocations. The lookup is case-insensitive.

Parameters:

  • name: Country name (e.g., "Sweden", "DENMARK", "norway")

Returns:

  • int: The UN M.49 numeric code as integer if found
  • bool: true if the name exists, false otherwise

Example:

if num, ok := NameToNumberInt("sweden"); ok {
    fmt.Println(num) // Output: 752
}

func NumberIntToAlpha2

func NumberIntToAlpha2(code int) (string, bool)

NumberIntToAlpha2 converts a UN M.49 numeric code (as integer) to its ISO 3166-1 alpha-2 code.

This function uses direct array indexing for O(1) performance with zero allocations. This is the fastest method for numeric to alpha conversions when you have an integer input.

Parameters:

  • code: UN M.49 numeric code as integer (e.g., 840, 4, 826)

Returns:

  • string: The corresponding alpha-2 code if found
  • bool: true if the conversion succeeded, false if the input code is invalid

Example:

if alpha2, ok := NumberIntToAlpha2(840); ok {
    fmt.Println(alpha2) // Output: US
}

Performance: Sub-nanosecond lookup time with zero allocations.

func NumberIntToAlpha3

func NumberIntToAlpha3(code int) (string, bool)

NumberIntToAlpha3 converts a UN M.49 numeric code (as integer) to its ISO 3166-1 alpha-3 code.

This function uses direct array indexing for O(1) performance with zero allocations. This is the fastest method for numeric to alpha conversions when you have an integer input.

Parameters:

  • code: UN M.49 numeric code as integer (e.g., 840, 4, 826)

Returns:

  • string: The corresponding alpha-3 code if found
  • bool: true if the conversion succeeded, false if the input code is invalid

Example:

if alpha3, ok := NumberIntToAlpha3(840); ok {
    fmt.Println(alpha3) // Output: USA
}

Performance: Sub-nanosecond lookup time with zero allocations.

func NumberIntToName

func NumberIntToName(code int) (string, bool)

NumberIntToName retrieves the country name for a UN M.49 numeric code (as integer).

This function uses direct array indexing for O(1) performance with zero allocations. This is the fastest method to get a country name from a numeric code.

Parameters:

  • code: UN M.49 numeric code as integer (e.g., 840, 4, 826)

Returns:

  • string: The country name if found
  • bool: true if the code exists, false otherwise

Example:

if name, ok := NumberIntToName(840); ok {
    fmt.Println(name) // Output: United States of America
}

Performance: Sub-nanosecond lookup time with zero allocations.

func NumberToAlpha2

func NumberToAlpha2(code string) (string, bool)

NumberToAlpha2 converts a UN M.49 numeric code to its ISO 3166-1 alpha-2 code.

This function performs an O(1) map lookup with zero memory allocations. The numeric code can include leading zeros.

Parameters:

  • code: UN M.49 numeric code as string (e.g., "276", "380", "724")

Returns:

  • string: The corresponding alpha-2 code if found
  • bool: true if the conversion succeeded, false if the input code is invalid

Example:

if alpha2, ok := NumberToAlpha2("276"); ok {
    fmt.Println(alpha2) // Output: DE
}

Note: For integer input, use NumberIntToAlpha2 for better performance.

func NumberToAlpha3

func NumberToAlpha3(code string) (string, bool)

NumberToAlpha3 converts a UN M.49 numeric code to its ISO 3166-1 alpha-3 code.

This function performs an O(1) map lookup with zero memory allocations. The numeric code can include leading zeros.

Parameters:

  • code: UN M.49 numeric code as string (e.g., "250", "620", "300")

Returns:

  • string: The corresponding alpha-3 code if found
  • bool: true if the conversion succeeded, false if the input code is invalid

Example:

if alpha3, ok := NumberToAlpha3("250"); ok {
    fmt.Println(alpha3) // Output: FRA
}

Note: For integer input, use NumberIntToAlpha3 for better performance.

func NumberToName

func NumberToName(code string) (string, bool)

NumberToName retrieves the country name for a UN M.49 numeric code.

This function performs an O(1) map lookup with zero memory allocations. The numeric code can include leading zeros.

Parameters:

  • code: UN M.49 numeric code as string (e.g., "276", "380", "724")

Returns:

  • string: The official English short name from ISO 3166-1
  • bool: true if the code exists, false otherwise

Example:

if name, ok := NumberToName("276"); ok {
    fmt.Println(name) // Output: Germany
}

Note: For integer input, use NumberIntToName for better performance.

Types

type Country

type Country struct {
	// Name is the official English short name from ISO 3166-1
	Name string

	// Alpha2 is the ISO 3166-1 alpha-2 two-letter country code (e.g., "US" for United States)
	Alpha2 string

	// Alpha3 is the ISO 3166-1 alpha-3 three-letter country code (e.g., "USA" for United States)
	Alpha3 string

	// CountryCode is the UN M.49 three-digit numeric code (e.g., "840" for United States)
	CountryCode string

	// ISO31662 is the ISO 3166-2 subdivision code prefix
	ISO31662 string

	// Region is the UN M.49 geographic region name (e.g., "Americas", "Europe", "Asia")
	Region string

	// SubRegion is the UN M.49 geographic sub-region name (e.g., "Northern America", "Southern Europe")
	SubRegion string

	// IntermediateRegion is the UN M.49 intermediate geographic region name (optional)
	IntermediateRegion string

	// RegionCode is the UN M.49 three-digit numeric code for the geographic region
	RegionCode string

	// SubRegionCode is the UN M.49 three-digit numeric code for the geographic sub-region
	SubRegionCode string

	// IntermediateRegionCode is the UN M.49 three-digit numeric code for the intermediate region
	IntermediateRegionCode string
}

Country represents complete country information aggregated from ISO 3166 and UN M.49 data sources. All fields are pre-populated at compile-time for zero-allocation access.

func GetByAlpha2

func GetByAlpha2(code string) (Country, bool)

GetByAlpha2 retrieves complete country information by ISO 3166-1 alpha-2 code.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive matching. It returns a pre-allocated Country struct. The input is case-insensitive.

Parameters:

  • code: ISO 3166-1 alpha-2 code (e.g., "FR", "de", "NL", "pl")

Returns:

  • Country: Complete country information with properly formatted codes if found
  • bool: true if the country code exists, false otherwise

Example:

if country, ok := GetByAlpha2("fr"); ok {
    fmt.Printf("%s has numeric code %s\n", country.Name, country.CountryCode)
}

func GetByAlpha3

func GetByAlpha3(code string) (Country, bool)

GetByAlpha3 retrieves complete country information by ISO 3166-1 alpha-3 code.

This function performs an O(1) lookup using packed keys for zero-allocation, case-insensitive matching. It returns a pre-allocated Country struct. The input is case-insensitive.

Parameters:

  • code: ISO 3166-1 alpha-3 code (e.g., "DEU", "esp", "ITA", "swe")

Returns:

  • Country: Complete country information with properly formatted codes if found
  • bool: true if the country code exists, false otherwise

Example:

if country, ok := GetByAlpha3("deu"); ok {
    fmt.Printf("%s has alpha-2 code %s\n", country.Name, country.Alpha2)
}

func GetByName

func GetByName(name string) (Country, bool)

GetByName retrieves complete country information by country name.

This function uses a hash table with linear probing for O(1) average-case lookups with zero allocations. The lookup is case-insensitive.

Parameters:

  • name: Country name (e.g., "Switzerland", "AUSTRIA", "portugal")

Returns:

  • Country: Complete country information with properly formatted codes if found
  • bool: true if the name exists, false otherwise

Example:

if country, ok := GetByName("switzerland"); ok {
    fmt.Printf("%s has alpha-2 code %s\n", country.Name, country.Alpha2)
}

func GetByNumber

func GetByNumber(code string) (Country, bool)

GetByNumber retrieves complete country information by UN M.49 numeric code.

This function uses an optimized array lookup for O(1) performance. The numeric code string is parsed inline without allocations.

Parameters:

  • code: UN M.49 numeric code as string (e.g., "840", "826", "250")

Returns:

  • Country: Complete country information if found
  • bool: true if the country code exists, false otherwise

Example:

if country, ok := GetByNumber("840"); ok {
    fmt.Printf("%s has alpha-2 code %s\n", country.Name, country.Alpha2)
}

Note: For integer-based lookups, use GetByNumberInt for better performance.

func GetByNumberInt

func GetByNumberInt(code int) (Country, bool)

GetByNumberInt retrieves complete country information by UN M.49 numeric code (as integer).

This function uses direct array indexing for O(1) performance with zero allocations. This is the fastest method to get full country information from a numeric code.

Parameters:

  • code: UN M.49 numeric code as integer (e.g., 840, 4, 826)

Returns:

  • Country: Complete country information if found
  • bool: true if the country code exists, false otherwise

Example:

if country, ok := GetByNumberInt(840); ok {
    fmt.Printf("%s has alpha-2 code %s\n", country.Name, country.Alpha2)
}

Performance: Sub-nanosecond lookup time with zero allocations.

Directories

Path Synopsis
cmd
generator command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL