inflect

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: MIT Imports: 2 Imported by: 0

README

go-inflect

A Go port of the Python inflect library for English word inflection.

  • 100+ functions — pluralization, articles, numbers, verbs, and more
  • Case-preserving — "CAT" → "CATS", "Child" → "Children"
  • Thread-safe — all functions safe for concurrent use
  • Template-readyFuncMap() for text/template and html/template
  • Minimal dependencies — only golang.org/x/text for Unicode normalization
  • Drop-in compatible with jinzhu/inflection and go-openapi/inflect

Installation

go get github.com/cv/go-inflect/v2

Quick Start

The easiest way to use go-inflect is with Go templates:

import (
    "os"
    "text/template"
    "github.com/cv/go-inflect/v2"
)

func main() {
    tmpl := template.New("report").Funcs(inflect.FuncMap())
    tmpl.Parse(`
📊 Build Report for {{.Project}}

{{.Tests}} {{plural "test" .Tests}} {{pastTense "run"}} in {{.Duration}} {{plural "second" .Duration}}.
Found {{no "error" .Errors}} and {{no "warning" .Warnings}}.

This is the {{ordinalWord .BuildNum}} build, and it {{pastTense "complete"}} {{comparative "fast"}}
than {{numberToWords .Improvement}}% of previous builds — {{possessive .Author}} {{superlative "good"}} yet!

Summary: {{join .Tags}}
`)
    tmpl.Execute(os.Stdout, map[string]any{
        "Project":     "go-inflect",
        "Tests":       142,
        "Duration":    3,
        "Errors":      0,
        "Warnings":    2,
        "BuildNum":    47,
        "Improvement": 85,
        "Author":      "James",
        "Tags":        []string{"fast", "stable", "passing"},
    })
}
// Output:
// 📊 Build Report for go-inflect
// 
// 142 tests ran in 3 seconds.
// Found no errors and 2 warnings.
// 
// This is the forty-seventh build, and it completed faster
// than eighty-five% of previous builds — James's best yet!
// 
// Summary: fast, stable, and passing

50+ template functions available — see FuncMap documentation for the complete list.

Direct Function Calls

All functions are also available for direct use:

// Pluralization handles irregular forms
inflect.Plural("person")             // "people"
inflect.Plural("criterion")          // "criteria"  
inflect.Singular("phenomena")        // "phenomenon"

// Verb conjugation
inflect.PastTense("run")             // "ran"
inflect.PastParticiple("write")      // "written"
inflect.PresentParticiple("swim")    // "swimming"

// Numbers in words
inflect.NumberToWords(42)            // "forty-two"
inflect.OrdinalWord(3)               // "third"
inflect.FractionToWords(3, 4)        // "three quarters"
inflect.CurrencyToWords(99.99, "USD") // "ninety-nine dollars and ninety-nine cents"

// Adjectives and adverbs
inflect.Comparative("beautiful")     // "more beautiful"
inflect.Superlative("fast")          // "fastest"
inflect.Adverb("quick")              // "quickly"

// Handy utilities
inflect.An("hour")                   // "an hour"
inflect.Join([]string{"a","b","c"})  // "a, b, and c"
inflect.No("error", 0)               // "no errors"
inflect.Possessive("James")          // "James's"

See pkg.go.dev for the complete API.

Custom Engine

For isolated configurations (different classical modes, custom definitions), create a separate engine:

// Classical Latin/Greek plurals
classical := inflect.NewEngine()
classical.Classical(true)
classical.Plural("formula")  // "formulae"
classical.Plural("cactus")   // "cacti"

// Modern English (default)
modern := inflect.NewEngine()
modern.Plural("formula")     // "formulas"

// Custom definitions
eng := inflect.NewEngine()
eng.DefNoun("regex", "regexen")
eng.DefNoun("pokemon", "pokemon")

// Use custom engine with templates
tmpl := template.New("custom").Funcs(eng.FuncMap())

Migration from jinzhu/inflection

Core functions work identically:

inflect.Plural("cat")       // "cats"
inflect.Singular("cats")    // "cat"
inflect.Underscore("Hello") // "hello"

Compatibility aliases: Pluralize, Singularize, Camelize, CamelizeDownFirst, AddIrregular, AddUncountable.

Documentation

Full API documentation: pkg.go.dev/github.com/cv/go-inflect/v2

License

MIT — see LICENSE

Acknowledgments

Documentation

Overview

Package inflect provides English language inflection utilities.

This package offers 100+ functions for pluralization, singularization, articles, numbers, ordinals, verb tenses, possessives, and more.

All package-level functions are safe for concurrent use. For isolated configurations (e.g., different classical mode settings), create separate Engine instances with NewEngine.

The easiest way to use this package is with Go templates via FuncMap:

tmpl := template.New("example").Funcs(inflect.FuncMap())
tmpl.Parse(`I have {{plural "cat" .Count}}`)

All functions are also available for direct use:

inflect.Plural("child")      // "children"
inflect.An("apple")          // "an apple"
inflect.NumberToWords(42)    // "forty-two"

Index

Constants

View Source
const PossessiveModern = impl.PossessiveModern
View Source
const PossessiveTraditional = impl.PossessiveTraditional

Variables

View Source
var ErrInvalidRoman = impl.ErrInvalidRoman

ErrInvalidRoman is returned when a Roman numeral string is malformed.

Functions

func A

func A(word string) string

A is an alias for An - returns word prefixed with appropriate indefinite article.

func AddIrregular

func AddIrregular(singular string, plural string)

AddIrregular is an alias for DefNoun, provided for compatibility with github.com/jinzhu/inflection.

Example:

AddIrregular("person", "people")
Plural("person") // returns "people"

func AddUncountable

func AddUncountable(words ...string)

AddUncountable marks words as uncountable (same singular and plural form), provided for compatibility with github.com/jinzhu/inflection and github.com/go-openapi/inflect.

Example:

AddUncountable("fish", "sheep")
Plural("fish")  // returns "fish"
Plural("sheep") // returns "sheep"

func Adverb

func Adverb(adj string) string

Adverb returns the adverb form of an English adjective.

Examples:

  • Adverb("quick") returns "quickly"
  • Adverb("happy") returns "happily"
  • Adverb("gentle") returns "gently"
  • Adverb("true") returns "truly"
  • Adverb("basic") returns "basically"
  • Adverb("good") returns "well"
  • Adverb("fast") returns "fast"

func An

func An(word string) string

An returns the word prefixed with the appropriate indefinite article ("a" or "an").

The selection follows standard English rules:

  • Use "an" before vowel sounds: "an apple", "an hour"
  • Use "a" before consonant sounds: "a cat", "a university"

Special cases handled:

  • Silent 'h': "an honest person"
  • Vowels with consonant sounds: "a Ukrainian", "a unanimous decision"
  • Abbreviations: "a YAML file", "a JSON object"

Custom patterns defined via DefA(), DefAn(), DefAPattern(), and DefAnPattern() take precedence over default rules.

func Asciify

func Asciify(word string) string

Asciify removes or transliterates non-ASCII characters from a string. Accented characters are converted to their ASCII equivalents where possible.

This function is provided for compatibility with github.com/go-openapi/inflect and Rails ActiveSupport.

Examples:

Asciify("café")    // "cafe"
Asciify("naïve")   // "naive"
Asciify("日本語")  // "" (non-Latin characters removed)

func CamelCase

func CamelCase(s string) string

CamelCase converts a string to camelCase.

It handles snake_case, kebab-case, and mixed inputs. First word is lowercase, subsequent words are capitalized, with no separators.

Examples:

  • CamelCase("hello_world") returns "helloWorld"
  • CamelCase("hello-world") returns "helloWorld"
  • CamelCase("hello world") returns "helloWorld"
  • CamelCase("HTTP_SERVER") returns "httpServer"

func Camelize

func Camelize(word string) string

Camelize is an alias for PascalCase, provided for compatibility with github.com/go-openapi/inflect.

Example:

Camelize("hello_world") // returns "HelloWorld"

func CamelizeDownFirst

func CamelizeDownFirst(word string) string

CamelizeDownFirst is an alias for CamelCase, provided for compatibility with github.com/go-openapi/inflect.

Example:

CamelizeDownFirst("hello_world") // returns "helloWorld"

func Capitalize

func Capitalize(s string) string

Capitalize capitalizes the first letter of a string.

Examples:

  • Capitalize("hello") returns "Hello"
  • Capitalize("HELLO") returns "HELLO"
  • Capitalize("") returns ""
  • Capitalize("hello world") returns "Hello world"

func Classical

func Classical(enabled bool)

Classical enables or disables classical pluralization mode.

This is an alias for ClassicalAll() for backward compatibility. It sets all classical pluralization options at once.

When enabled (true), Plural() prefers classical Latin/Greek plural forms:

  • formula -> formulae (instead of formulas)
  • antenna -> antennae (instead of antennas)
  • vertebra -> vertebrae (instead of vertebras)
  • alumna -> alumnae (instead of alumnas)

When disabled (false, the default), modern English plurals are used.

Examples:

Classical(true)
Plural("formula") // returns "formulae"
Classical(false)
Plural("formula") // returns "formulas"

func ClassicalAll

func ClassicalAll(enabled bool)

ClassicalAll enables or disables all classical pluralization options at once.

This is a master switch that sets all classical options:

  • classicalAll: master switch
  • classicalZero: 0 cat vs 0 cats
  • classicalHerd: wildebeest vs wildebeests
  • classicalNames: proper name pluralization
  • classicalAncient: Latin/Greek forms (formulae vs formulas)
  • classicalPersons: persons vs people

When enabled (true), Plural() prefers classical Latin/Greek plural forms:

  • formula -> formulae (instead of formulas)
  • antenna -> antennae (instead of antennas)
  • vertebra -> vertebrae (instead of vertebras)
  • alumna -> alumnae (instead of alumnas)

When disabled (false, the default), modern English plurals are used.

Examples:

ClassicalAll(true)
Plural("formula") // returns "formulae"
ClassicalAll(false)
Plural("formula") // returns "formulas"

func ClassicalAncient

func ClassicalAncient(enabled bool)

ClassicalAncient enables or disables classical Latin/Greek plural forms.

This controls the classicalAncient flag independently of other classical options like classicalZero, classicalHerd, classicalNames, and classicalPersons.

When enabled (true), Plural() prefers classical Latin/Greek plural forms:

  • formula -> formulae (instead of formulas)
  • antenna -> antennae (instead of antennas)
  • vertebra -> vertebrae (instead of vertebras)
  • alumna -> alumnae (instead of alumnas)

When disabled (false, the default), modern English plurals are used.

Note: This also controls the legacy classicalMode flag, since both affect Latin/Greek plural forms.

Examples:

ClassicalAncient(true)
Plural("formula") // returns "formulae"
ClassicalAncient(false)
Plural("formula") // returns "formulas"

func ClassicalHerd

func ClassicalHerd(enabled bool)

ClassicalHerd enables or disables classical herd animal pluralization.

This controls the classicalHerd flag independently of other classical options like classicalZero, classicalNames, classicalAncient, and classicalPersons.

When enabled (true), Plural() uses unchanged forms for herd animals:

  • bison -> bison
  • buffalo -> buffalo
  • wildebeest -> wildebeest

When disabled (false, the default), modern English plurals are used:

  • bison -> bisons
  • buffalo -> buffaloes
  • wildebeest -> wildebeests

Note: Some animals like deer, sheep, moose always remain unchanged regardless of this setting.

Examples:

ClassicalHerd(true)
Plural("wildebeest") // returns "wildebeest"
ClassicalHerd(false)
Plural("wildebeest") // returns "wildebeests"

func ClassicalNames

func ClassicalNames(enabled bool)

ClassicalNames enables or disables classical proper name pluralization.

This controls the classicalNames flag independently of other classical options like classicalZero, classicalHerd, classicalAncient, and classicalPersons.

When enabled (true), Plural() leaves proper names ending in 's' unchanged:

  • Jones -> Jones (unchanged)
  • Williams -> Williams (unchanged)
  • Hastings -> Hastings (unchanged)

When disabled (false, the default), regular pluralization rules apply:

  • Jones -> Joneses
  • Williams -> Williamses
  • Hastings -> Hastingses

Note: This only affects capitalized words ending in 's'. Other proper names like "Mary" still pluralize normally (Mary -> Marys).

Examples:

ClassicalNames(true)
Plural("Jones") // returns "Jones"
ClassicalNames(false)
Plural("Jones") // returns "Joneses"

func ClassicalPersons

func ClassicalPersons(enabled bool)

ClassicalPersons enables or disables classical person/persons pluralization.

This controls the classicalPersons flag independently of other classical options like classicalZero, classicalHerd, classicalNames, and classicalAncient.

When enabled (true), Plural() uses "persons" as the plural of "person":

  • person -> persons

When disabled (false, the default), the irregular plural "people" is used:

  • person -> people

Examples:

ClassicalPersons(true)
Plural("person") // returns "persons"
ClassicalPersons(false)
Plural("person") // returns "people"

func ClassicalZero

func ClassicalZero(enabled bool)

ClassicalZero enables or disables classical zero count pluralization.

This controls the classicalZero flag independently of other classical options like classicalHerd, classicalNames, classicalAncient, and classicalPersons.

When enabled (true), No() uses singular form for zero count:

  • No("cat", 0) -> "no cat"

When disabled (false, the default), No() uses plural form for zero count:

  • No("cat", 0) -> "no cats"

Examples:

ClassicalZero(true)
No("cat", 0) // returns "no cat"
ClassicalZero(false)
No("cat", 0) // returns "no cats"

func Comparative

func Comparative(adj string) string

Comparative returns the comparative form of an English adjective.

Examples:

  • Comparative("big") returns "bigger"
  • Comparative("happy") returns "happier"
  • Comparative("beautiful") returns "more beautiful"
  • Comparative("good") returns "better"

func Compare

func Compare(word1 string, word2 string) string

Compare compares two words for singular/plural equality.

It returns:

  • "eq" if the words are equal (case-insensitive)
  • "s:p" if word1 is singular and word2 is its plural form
  • "p:s" if word1 is plural and word2 is its singular form
  • "p:p" if both words are different plural forms of the same word
  • "" if the words are not related

Examples:

  • Compare("cat", "cat") returns "eq"
  • Compare("cat", "cats") returns "s:p"
  • Compare("cats", "cat") returns "p:s"
  • Compare("indexes", "indices") returns "p:p"
  • Compare("cat", "dog") returns ""

func CompareAdjs

func CompareAdjs(adj1 string, adj2 string) string

CompareAdjs compares two adjectives for singular/plural equality.

This compares adjectives using adjective pluralization rules (demonstratives, articles, possessives).

It returns:

  • "eq" if the adjectives are equal (case-insensitive)
  • "s:p" if adj1 is singular and adj2 is its plural form
  • "p:s" if adj1 is plural and adj2 is its singular form
  • "" if the adjectives are not related

Examples:

  • CompareAdjs("this", "these") returns "s:p"
  • CompareAdjs("that", "those") returns "s:p"
  • CompareAdjs("these", "this") returns "p:s"
  • CompareAdjs("a", "some") returns "s:p"

func CompareNouns

func CompareNouns(noun1 string, noun2 string) string

CompareNouns compares two nouns for singular/plural equality.

This is an alias for Compare that makes the intent explicit when working specifically with nouns.

It returns:

  • "eq" if the nouns are equal (case-insensitive)
  • "s:p" if noun1 is singular and noun2 is its plural form
  • "p:s" if noun1 is plural and noun2 is its singular form
  • "p:p" if both nouns are different plural forms of the same word
  • "" if the nouns are not related

Examples:

  • CompareNouns("cat", "cats") returns "s:p"
  • CompareNouns("mice", "mouse") returns "p:s"

func CompareVerbs

func CompareVerbs(verb1 string, verb2 string) string

CompareVerbs compares two verbs for singular/plural equality.

This compares verbs using verb pluralization rules (3rd person singular vs base form).

It returns:

  • "eq" if the verbs are equal (case-insensitive)
  • "s:p" if verb1 is singular (3rd person) and verb2 is its plural (base form)
  • "p:s" if verb1 is plural (base form) and verb2 is its singular (3rd person)
  • "" if the verbs are not related

Examples:

  • CompareVerbs("runs", "run") returns "s:p" (3rd person to base)
  • CompareVerbs("run", "runs") returns "p:s" (base to 3rd person)
  • CompareVerbs("is", "are") returns "s:p"
  • CompareVerbs("has", "have") returns "s:p"

func CountSyllables

func CountSyllables(word string) int

CountSyllables estimates the number of syllables in a word using a heuristic based on vowel groups. It provides reasonable estimates for most English words but may not be 100% accurate for all words, especially those with unusual spelling patterns or borrowed words.

The algorithm:

  • Counts groups of consecutive vowels (a, e, i, o, u, y) as one syllable
  • Handles silent 'e' at the end of words
  • Returns at least 1 for any non-empty word
  • Returns 0 for empty strings

func CountingWord

func CountingWord(n int) string

CountingWord converts an integer to its counting word representation.

This provides frequency/repetition words:

  • 1 returns "once"
  • 2 returns "twice"
  • 3 returns "thrice"
  • 4+ returns the number word followed by "times" (e.g., "four times")
  • 0 returns "zero times"
  • Negative numbers are prefixed with "negative" (e.g., "negative once")

Examples:

  • CountingWord(1) returns "once"
  • CountingWord(2) returns "twice"
  • CountingWord(3) returns "thrice"
  • CountingWord(4) returns "four times"
  • CountingWord(10) returns "ten times"
  • CountingWord(0) returns "zero times"
  • CountingWord(-1) returns "negative once"
  • CountingWord(-2) returns "negative twice"

func CountingWordThreshold

func CountingWordThreshold(n int, threshold int) string

CountingWordThreshold converts an integer to its counting word representation only if the number is below the specified threshold. If the number is greater than or equal to the threshold, it returns the number as digits followed by "times".

This is useful for making text more readable by spelling out small numbers while keeping larger numbers in digit form.

Examples:

  • CountingWordThreshold(5, 10) returns "five times" (5 < 10, convert to words)
  • CountingWordThreshold(15, 10) returns "15 times" (15 >= 10, return as digits)
  • CountingWordThreshold(1, 10) returns "once" (special word for 1)
  • CountingWordThreshold(2, 10) returns "twice" (special word for 2)
  • CountingWordThreshold(3, 10) returns "thrice" (special word for 3)
  • CountingWordThreshold(100, 100) returns "100 times" (100 >= 100, return as digits)
  • CountingWordThreshold(-3, 10) returns "negative thrice" (-3 < 10, convert to words)

func CountingWordWithOptions

func CountingWordWithOptions(n int, useThrice bool) string

CountingWordWithOptions converts an integer to its counting word representation with control over whether to use "thrice" for 3.

When useThrice is true, 3 returns "thrice". When useThrice is false, 3 returns "three times".

Examples:

  • CountingWordWithOptions(3, true) returns "thrice"
  • CountingWordWithOptions(3, false) returns "three times"
  • CountingWordWithOptions(1, false) returns "once"
  • CountingWordWithOptions(-3, true) returns "negative thrice"
  • CountingWordWithOptions(-3, false) returns "negative three times"

func CurrencyToWords

func CurrencyToWords(amount float64, currency string) string

CurrencyToWords converts a currency amount to its English word representation.

The function handles various cases:

  • Proper singular/plural forms based on amount
  • Zero minor units are omitted (e.g., "one hundred dollars" not "one hundred dollars and zero cents")
  • Minor units only when major is zero (e.g., "fifty cents")
  • Negative amounts are prefixed with "negative"
  • Amounts are rounded to 2 decimal places

Supported currency codes: USD, GBP, EUR, CAD, AUD, JPY, CHF, CNY, INR. Returns empty string for unknown currency codes.

Examples:

  • CurrencyToWords(123.45, "USD") returns "one hundred twenty-three dollars and forty-five cents"
  • CurrencyToWords(1.00, "USD") returns "one dollar"
  • CurrencyToWords(0.50, "USD") returns "fifty cents"
  • CurrencyToWords(1000000.00, "USD") returns "one million dollars"
  • CurrencyToWords(123.45, "GBP") returns "one hundred twenty-three pounds and forty-five pence"
  • CurrencyToWords(-5.00, "USD") returns "negative five dollars"

func Dasherize

func Dasherize(s string) string

Dasherize converts a string to kebab-case.

It handles PascalCase, camelCase, snake_case, and mixed inputs. Consecutive uppercase letters (like "HTTP") are kept together as one word.

Examples:

  • Dasherize("HelloWorld") returns "hello-world"
  • Dasherize("hello_world") returns "hello-world"
  • Dasherize("HTTPServer") returns "http-server"
  • Dasherize("getHTTPResponse") returns "get-http-response"
  • Dasherize("already-kebab") returns "already-kebab"

func DefA

func DefA(word string)

DefA defines a custom pattern that forces "a" instead of "an" for a word.

The pattern is matched against the first word of the input (case-insensitive). Custom "a" patterns take precedence over custom "an" patterns and default rules.

Examples:

DefA("ape")
An("ape") // returns "a ape" instead of "an ape"
An("Ape") // returns "a Ape" (case-insensitive matching)

func DefAPattern

func DefAPattern(pattern string) error

DefAPattern defines a regex pattern that forces "a" instead of "an".

The pattern is matched against the lowercase first word of the input. The pattern must be a valid Go regex. Patterns are matched with full-string matching (automatically anchored with ^ and $).

Pattern priorities (highest to lowest):

  1. Exact word matches (DefA)
  2. Exact word matches (DefAn)
  3. Regex patterns (DefAPattern)
  4. Regex patterns (DefAnPattern)
  5. Default rules

Returns an error if the pattern is invalid.

Examples:

DefAPattern("euro.*")
An("euro")     // returns "a euro"
An("european") // returns "a european"
An("eurozone") // returns "a eurozone"

func DefAReset

func DefAReset()

DefAReset resets all custom a/an patterns to defaults (empty).

This removes all custom patterns added via DefA(), DefAn(), DefAPattern(), and DefAnPattern().

Example:

DefA("ape")
DefAn("hero")
DefAPattern("euro.*")
DefAnPattern("honor.*")
DefAReset()
An("ape")       // returns "an ape" (default rule)
An("hero")      // returns "a hero" (default rule)
An("european")  // returns "an european" (default rule)
An("honorable") // returns "a honorable" (default rule)

func DefAdj

func DefAdj(singular string, plural string)

DefAdj defines a custom adjective pluralization rule.

NOTE: This is a placeholder stub for future implementation. Full adjective pluralization is not yet implemented; this function only stores the singular/plural pair in internal maps for future use.

The singular and plural forms are stored in lowercase.

Examples:

DefAdj("big", "bigs")
DefAdj("happy", "happies")

func DefAdjReset

func DefAdjReset()

DefAdjReset resets all custom adjective pluralization rules.

NOTE: This is a placeholder stub for future implementation.

This removes all custom rules added via DefAdj().

func DefAn

func DefAn(word string)

DefAn defines a custom pattern that forces "an" instead of "a" for a word.

The pattern is matched against the first word of the input (case-insensitive). Custom "an" patterns take precedence over default rules but not custom "a" patterns.

Examples:

DefAn("hero")
An("hero") // returns "an hero" instead of "a hero"
An("Hero") // returns "an Hero" (case-insensitive matching)

func DefAnPattern

func DefAnPattern(pattern string) error

DefAnPattern defines a regex pattern that forces "an" instead of "a".

The pattern is matched against the lowercase first word of the input. The pattern must be a valid Go regex. Patterns are matched with full-string matching (automatically anchored with ^ and $).

Pattern priorities (highest to lowest):

  1. Exact word matches (DefA)
  2. Exact word matches (DefAn)
  3. Regex patterns (DefAPattern)
  4. Regex patterns (DefAnPattern)
  5. Default rules

Returns an error if the pattern is invalid.

Examples:

DefAnPattern("honor.*")
An("honor")     // returns "an honor"
An("honorable") // returns "an honorable"
An("honorary")  // returns "an honorary"

func DefNoun

func DefNoun(singular string, plural string)

DefNoun defines a custom noun pluralization rule.

The singular and plural forms are stored in lowercase, and subsequent calls to Plural() and Singular() will use this custom rule with case preservation.

Examples:

DefNoun("foo", "foos")
Plural("foo") // returns "foos"
Plural("Foo") // returns "Foos"
Singular("foos") // returns "foo"

func DefNounReset

func DefNounReset()

DefNounReset resets all noun pluralization rules to their defaults.

This removes all custom rules added via DefNoun() and restores any built-in rules that may have been overwritten.

Example:

DefNoun("child", "childs")  // override built-in
DefNoun("foo", "foos")      // add custom
DefNounReset()
Plural("child") // returns "children" (restored)
Plural("foo")   // returns "foos" (standard rule, custom removed)

func DefVerb

func DefVerb(singular string, plural string)

DefVerb defines a custom verb conjugation rule.

NOTE: This is a placeholder stub for future implementation. Full verb conjugation is not yet implemented; this function only stores the singular/plural pair in internal maps for future use.

The singular and plural forms are stored in lowercase.

Examples:

DefVerb("run", "runs")
DefVerb("be", "are")

func DefVerbReset

func DefVerbReset()

DefVerbReset resets all custom verb conjugation rules.

NOTE: This is a placeholder stub for future implementation.

This removes all custom rules added via DefVerb().

func DefaultEngine

func DefaultEngine() *impl.Engine

DefaultEngine returns the default package-level Engine. This can be used to access Engine methods directly or to configure the default behavior.

The returned Engine is safe for concurrent use; all methods are protected by an internal mutex. However, callers should be aware that modifications to the default Engine affect all package-level function calls globally.

For isolated configurations, use NewEngine() to create a separate instance.

Examples:

// Access the default engine directly
e := inflect.DefaultEngine()
e.Classical(true)
e.Plural("formula") // returns "formulae"

// All package-level calls use the same engine
inflect.Plural("formula") // also returns "formulae"

func ForeignKey

func ForeignKey(word string) string

ForeignKey creates an underscored foreign key name from a type name.

This function is provided for compatibility with github.com/go-openapi/inflect and Rails ActiveSupport.

Examples:

ForeignKey("Person")     // "person_id"
ForeignKey("Message")    // "message_id"
ForeignKey("AdminUser")  // "admin_user_id"

func ForeignKeyCondensed

func ForeignKeyCondensed(word string) string

ForeignKeyCondensed creates a foreign key name without an underscore before "id".

This function is provided for compatibility with github.com/go-openapi/inflect and Rails ActiveSupport.

Examples:

ForeignKeyCondensed("Person")     // "personid"
ForeignKeyCondensed("Message")    // "messageid"
ForeignKeyCondensed("AdminUser")  // "admin_userid"

func FormatNumber

func FormatNumber(n int) string

FormatNumber formats an integer with commas as thousand separators.

Examples:

  • FormatNumber(1000) returns "1,000"
  • FormatNumber(1000000) returns "1,000,000"
  • FormatNumber(123456789) returns "123,456,789"
  • FormatNumber(-1234) returns "-1,234"
  • FormatNumber(999) returns "999" (no comma needed)

func FractionToWords

func FractionToWords(numerator int, denominator int) string

FractionToWords converts a fraction to its English word representation.

Special cases are handled as follows:

  • Denominator 2: uses "half/halves"
  • Denominator 4: uses "quarter/quarters"
  • Other denominators: uses ordinal form (third, fifth, eighth, etc.)
  • Numerator 1: singular form (one third)
  • Numerator > 1: plural form (two thirds)
  • Denominator 1: returns just the numerator in words
  • Denominator 0: returns empty string (invalid fraction)

Negative numbers are handled by prefixing "negative" when the overall fraction is negative (exactly one of numerator or denominator is negative).

Examples:

  • FractionToWords(1, 2) returns "one half"
  • FractionToWords(3, 2) returns "three halves"
  • FractionToWords(1, 4) returns "one quarter"
  • FractionToWords(3, 4) returns "three quarters"
  • FractionToWords(2, 3) returns "two thirds"
  • FractionToWords(5, 8) returns "five eighths"
  • FractionToWords(1, 100) returns "one hundredth"
  • FractionToWords(-1, 2) returns "negative one half"

func FractionToWordsWithFourths

func FractionToWordsWithFourths(numerator int, denominator int) string

FractionToWordsWithFourths converts a fraction to its English word representation, using "fourth/fourths" instead of "quarter/quarters" for denominator 4.

This is an alternative style that some prefer for mathematical contexts.

Examples:

  • FractionToWordsWithFourths(1, 4) returns "one fourth"
  • FractionToWordsWithFourths(3, 4) returns "three fourths"

func FuncMap

func FuncMap() template.FuncMap

FuncMap returns a template.FuncMap containing inflection functions for use with Go's text/template and html/template packages.

The returned FuncMap includes the following functions (using camelCase names):

Pluralization and Singularization:

  • plural(word string, count ...int) string - Plural form of a noun
  • pluralize(word string) string - Alias for plural
  • singular(word string) string - Singular form of a noun
  • singularize(word string) string - Alias for singular
  • pluralNoun(word string, count ...int) string - Plural form with pronoun support
  • pluralVerb(word string, count ...int) string - Plural form of a verb
  • pluralAdj(word string, count ...int) string - Plural form of an adjective
  • singularNoun(word string, count ...int) string - Singular form with pronoun support

Articles:

  • an(word string) string - Prefixes word with "a" or "an"
  • a(word string) string - Alias for an()

Numbers and Ordinals:

  • ordinal(n int) string - Ordinal with suffix: 1 -> "1st"
  • ordinalSuffix(n int) string - Just the suffix: 1 -> "st"
  • ordinalWord(n int) string - Ordinal in words: 1 -> "first"
  • ordinalToCardinal(s string) string - "first" -> "one"
  • wordToOrdinal(s string) string - "one" -> "first"
  • numberToWords(n int) string - Number in words: 42 -> "forty-two"
  • numberToWordsWithAnd(n int) string - With "and": 123 -> "one hundred and twenty-three"
  • formatNumber(n int) string - With commas: 1000 -> "1,000"
  • countingWord(n int) string - 1 -> "once", 2 -> "twice", 3 -> "3 times"
  • fractionToWords(num, denom int) string - 1,4 -> "one quarter"
  • currencyToWords(amount float64, currency string) string - 1.50, "USD" -> "one dollar and fifty cents"
  • no(word string, count int) string - 0 -> "no cats", 1 -> "1 cat"

Verb Tenses:

  • pastTense(verb string) string - Past tense: "walk" -> "walked"
  • pastParticiple(verb string) string - Past participle: "take" -> "taken"
  • presentParticiple(verb string) string - Present participle: "run" -> "running"
  • futureTense(verb string) string - Future tense: "walk" -> "will walk"

Adjectives and Adverbs:

  • comparative(adj string) string - Comparative form: "big" -> "bigger"
  • superlative(adj string) string - Superlative form: "big" -> "biggest"
  • adverb(adj string) string - Adverb form: "quick" -> "quickly"

Possessives:

  • possessive(word string) string - Possessive form: "cat" -> "cat's"

List Formatting:

  • join(words []string) string - Join with Oxford comma: ["a","b","c"] -> "a, b, and c"
  • joinWith(words []string, conj string) string - Join with custom conjunction

Case Conversion:

  • camelCase(s string) string - Convert to camelCase
  • snakeCase(s string) string - Convert to snake_case
  • underscore(s string) string - Alias for snakeCase
  • kebabCase(s string) string - Convert to kebab-case
  • dasherize(s string) string - Alias for kebabCase
  • pascalCase(s string) string - Convert to PascalCase
  • titleCase(s string) string - Alias for pascalCase
  • camelize(s string) string - Alias for pascalCase
  • camelizeDownFirst(s string) string - Alias for camelCase

Text Transformation:

  • capitalize(s string) string - Capitalize first letter: "hello" -> "Hello"
  • titleize(s string) string - Capitalize each word: "hello world" -> "Hello World"
  • humanize(s string) string - Human readable: "employee_salary" -> "Employee salary"

Rails-style Helpers:

  • tableize(word string) string - Type to table: "Person" -> "people"
  • foreignKey(word string) string - Type to FK: "User" -> "user_id"
  • typeify(word string) string - Table to type: "user_posts" -> "UserPost"
  • parameterize(word string) string - URL slug: "Hello World" -> "hello-world"
  • asciify(word string) string - Remove diacritics: "café" -> "cafe"

Utility:

  • wordCount(text string) int - Count words in text
  • countSyllables(word string) int - Count syllables in word

Example usage:

tmpl := template.New("example").Funcs(inflect.FuncMap())
tmpl.Parse(`I have {{plural "cat" .Count}} and {{an "apple"}}`)

// With count parameter:
tmpl.Parse(`There {{if eq .Count 1}}is{{else}}are{{end}} {{plural "item" .Count}}`)

For custom engine configurations, use Engine.FuncMap() instead.

func FutureTense

func FutureTense(verb string) string

FutureTense returns the future tense form of an English verb using "will".

Examples:

  • FutureTense("walk") returns "will walk"
  • FutureTense("go") returns "will go"
  • FutureTense("be") returns "will be"
  • FutureTense("WALK") returns "WILL WALK"
  • FutureTense("Walk") returns "Will Walk"

func Gender

func Gender(g string)

Gender sets the gender for singular third-person pronouns.

The gender affects pronoun selection in SingularNoun():

  • Gender("m") - masculine: they -> he, them -> him, their -> his
  • Gender("f") - feminine: they -> she, them -> her, their -> hers
  • Gender("n") - neuter: they -> it, them -> it, their -> its
  • Gender("t") - they (singular they): they -> they, them -> them, their -> their

The default gender is "t" (singular they).

Invalid gender values are ignored; the gender remains unchanged.

Examples:

Gender("m")
GetGender() // returns "m"
Gender("f")
GetGender() // returns "f"
Gender("invalid")
GetGender() // returns "f" (unchanged)

func GetGender

func GetGender() string

GetGender returns the current gender setting for singular third-person pronouns.

Returns one of:

  • "m" - masculine
  • "f" - feminine
  • "n" - neuter
  • "t" - they (singular they, the default)

Examples:

GetGender() // returns "t" (default)
Gender("m")
GetGender() // returns "m"

func GetNum

func GetNum() int

GetNum retrieves the current default count.

Returns 0 if no default has been set or if it was cleared.

Examples:

  • After Num(5): GetNum() returns 5
  • After Num(0) or Num(): GetNum() returns 0
  • Before any Num() call: GetNum() returns 0

func GetPossessiveStyle

func GetPossessiveStyle() impl.PossessiveStyleType

GetPossessiveStyle returns the current possessive style setting.

func Humanize

func Humanize(word string) string

Humanize converts an underscored or dasherized string into a human-readable form. It capitalizes the first letter, replaces underscores and dashes with spaces, and strips trailing "_id" suffixes.

This function is provided for compatibility with github.com/go-openapi/inflect and Rails ActiveSupport.

Examples:

Humanize("employee_salary")  // "Employee salary"
Humanize("author_id")        // "Author"
Humanize("hello-world")      // "Hello world"
Humanize("XMLParser")        // "Xml parser"

func IntToRoman added in v2.1.0

func IntToRoman(n int) string

IntToRoman converts an integer to its Roman numeral representation.

Roman numerals are only defined for integers from 1 to 3999. For values outside this range, an empty string is returned.

Examples:

  • IntToRoman(4) returns "IV"
  • IntToRoman(9) returns "IX"
  • IntToRoman(1984) returns "MCMLXXXIV"
  • IntToRoman(2025) returns "MMXXV"
  • IntToRoman(0) returns ""
  • IntToRoman(4000) returns ""

func IsClassical

func IsClassical() bool

IsClassical returns whether classical pluralization mode is enabled.

Returns true if Classical(true) or ClassicalAll(true) was called, false otherwise. This checks the classicalAncient flag which controls Latin/Greek plurals.

Examples:

IsClassical() // returns false (default)
Classical(true)
IsClassical() // returns true
Classical(false)
IsClassical() // returns false

func IsClassicalAll

func IsClassicalAll() bool

IsClassicalAll returns whether all classical pluralization options are enabled.

Returns true only if all classical options are enabled, false otherwise.

Examples:

IsClassicalAll() // returns false (default)
ClassicalAll(true)
IsClassicalAll() // returns true
ClassicalAll(false)
IsClassicalAll() // returns false

func IsClassicalAncient

func IsClassicalAncient() bool

IsClassicalAncient returns whether classical Latin/Greek plural forms are enabled.

Returns true if ClassicalAncient(true), Classical(true), or ClassicalAll(true) was called, false otherwise.

Examples:

IsClassicalAncient() // returns false (default)
ClassicalAncient(true)
IsClassicalAncient() // returns true
ClassicalAncient(false)
IsClassicalAncient() // returns false

func IsClassicalHerd

func IsClassicalHerd() bool

IsClassicalHerd returns whether classical herd animal pluralization is enabled.

Returns true if ClassicalHerd(true) or ClassicalAll(true) was called, false otherwise.

Examples:

IsClassicalHerd() // returns false (default)
ClassicalHerd(true)
IsClassicalHerd() // returns true
ClassicalHerd(false)
IsClassicalHerd() // returns false

func IsClassicalNames

func IsClassicalNames() bool

IsClassicalNames returns whether classical proper name pluralization is enabled.

Returns true if ClassicalNames(true) or ClassicalAll(true) was called, false otherwise.

Examples:

IsClassicalNames() // returns false (default)
ClassicalNames(true)
IsClassicalNames() // returns true
ClassicalNames(false)
IsClassicalNames() // returns false

func IsClassicalPersons

func IsClassicalPersons() bool

IsClassicalPersons returns whether classical person/persons pluralization is enabled.

Returns true if ClassicalPersons(true) or ClassicalAll(true) was called, false otherwise.

Examples:

IsClassicalPersons() // returns false (default)
ClassicalPersons(true)
IsClassicalPersons() // returns true
ClassicalPersons(false)
IsClassicalPersons() // returns false

func IsClassicalZero

func IsClassicalZero() bool

IsClassicalZero returns whether classical zero count pluralization is enabled.

Returns true if ClassicalZero(true) or ClassicalAll(true) was called, false otherwise.

Examples:

IsClassicalZero() // returns false (default)
ClassicalZero(true)
IsClassicalZero() // returns true
ClassicalZero(false)
IsClassicalZero() // returns false

func IsOrdinal

func IsOrdinal(s string) bool

IsOrdinal checks if a string is an ordinal (either numeric like "1st" or word like "first").

Examples:

  • IsOrdinal("1st") returns true
  • IsOrdinal("first") returns true
  • IsOrdinal("twenty-first") returns true
  • IsOrdinal("1") returns false
  • IsOrdinal("one") returns false
  • IsOrdinal("cat") returns false

func IsParticiple

func IsParticiple(word string) bool

IsParticiple checks if a word is a participle (present or past).

Examples:

  • IsParticiple("running") returns true (present participle)
  • IsParticiple("walked") returns true (past participle)
  • IsParticiple("taken") returns true (irregular past participle)
  • IsParticiple("walk") returns false (base verb)
  • IsParticiple("cat") returns false (not a verb form)

func IsPlural

func IsPlural(word string) bool

IsPlural checks if a word appears to be in plural form.

This function checks if the word is different from its singular form, indicating it's likely a plural. Note that this is heuristic and may not be accurate for all words, especially irregular forms.

Examples:

  • IsPlural("cats") returns true
  • IsPlural("cat") returns false
  • IsPlural("children") returns true
  • IsPlural("child") returns false
  • IsPlural("sheep") returns false (unchanged plurals are ambiguous)

func IsSingular

func IsSingular(word string) bool

IsSingular checks if a word appears to be in singular form.

This function returns true if the word is NOT plural. It's the logical inverse of IsPlural for most cases.

Examples:

  • IsSingular("cat") returns true
  • IsSingular("cats") returns false
  • IsSingular("child") returns true
  • IsSingular("children") returns false
  • IsSingular("sheep") returns true (unchanged plurals default to singular)

func Join

func Join(words []string) string

Join combines a slice of strings into a grammatically correct English list.

The function uses the Oxford comma (serial comma) for lists of three or more items. It uses "and" as the conjunction. For custom conjunctions, use JoinWithConj.

Examples:

  • Join([]string{}) returns ""
  • Join([]string{"a"}) returns "a"
  • Join([]string{"a", "b"}) returns "a and b"
  • Join([]string{"a", "b", "c"}) returns "a, b, and c"

func JoinNoOxford

func JoinNoOxford(words []string) string

JoinNoOxford combines a slice of strings without the Oxford comma.

Unlike Join, this function omits the comma before the final conjunction. Use this for non-Oxford comma style lists.

Examples:

  • JoinNoOxford([]string{"a", "b"}) returns "a and b"
  • JoinNoOxford([]string{"a", "b", "c"}) returns "a, b and c"

func JoinNoOxfordWithConj

func JoinNoOxfordWithConj(words []string, conj string) string

JoinNoOxfordWithConj combines a slice of strings without the Oxford comma using a custom conjunction.

Examples:

  • JoinNoOxfordWithConj([]string{"a", "b", "c"}, "or") returns "a, b or c"
  • JoinNoOxfordWithConj([]string{"a", "b", "c"}, "and") returns "a, b and c"

func JoinWithAutoSep

func JoinWithAutoSep(words []string, conj string) string

JoinWithAutoSep combines a slice of strings into a grammatically correct English list with a custom conjunction, automatically choosing the separator based on content.

If any item contains a comma, semicolons are used as separators ("; "). Otherwise, commas are used (", ").

This is useful when you don't know in advance whether items contain commas.

Examples:

  • JoinWithAutoSep([]string{"a", "b", "c"}, "and") returns "a, b, and c"
  • JoinWithAutoSep([]string{"Jan 1, 2020", "Feb 2, 2021"}, "and") returns "Jan 1, 2020; and Feb 2, 2021"

func JoinWithConj

func JoinWithConj(words []string, conj string) string

JoinWithConj combines a slice of strings into a grammatically correct English list with a custom conjunction.

The function uses the Oxford comma (serial comma) for lists of three or more items.

Examples:

  • JoinWithConj([]string{"a", "b"}, "or") returns "a or b"
  • JoinWithConj([]string{"a", "b", "c"}, "or") returns "a, b, or c"
  • JoinWithConj([]string{"a", "b", "c"}, "and/or") returns "a, b, and/or c"

func JoinWithFinalSep

func JoinWithFinalSep(words []string, conj string, sep string, finalSep string) string

JoinWithFinalSep combines a slice of strings with a custom separator and a different final separator (before the conjunction).

This allows for maximum flexibility in list formatting.

Examples:

  • JoinWithFinalSep([]string{"a", "b", "c"}, "and", ", ", "; ") returns "a, b; and c"
  • JoinWithFinalSep([]string{"a", "b", "c"}, "and", ", ", "") returns "a, b and c" (no Oxford comma)

func JoinWithSep

func JoinWithSep(words []string, conj string, sep string) string

JoinWithSep combines a slice of strings into a grammatically correct English list with a custom conjunction and separator.

This is useful when list items themselves contain commas.

Examples:

  • JoinWithSep([]string{"a", "b", "c"}, "and", "; ") returns "a; b; and c"
  • JoinWithSep([]string{"Jan 1, 2020", "Feb 2, 2021"}, "and", "; ") returns "Jan 1, 2020; and Feb 2, 2021"

func KebabCase

func KebabCase(s string) string

KebabCase is an alias for Dasherize. It converts a string to kebab-case.

Examples:

  • KebabCase("HelloWorld") returns "hello-world"
  • KebabCase("HTTPServer") returns "http-server"

func NewEngine

func NewEngine() *impl.Engine

NewEngine creates a new Engine instance with default settings.

Default settings:

  • All classical flags are false
  • irregularPlurals is initialized from defaultIrregularPlurals
  • singularIrregulars is built as the reverse of irregularPlurals
  • All custom maps are empty
  • Gender is "t" (singular they)
  • Possessive style is PossessiveModern
  • Default number is 0

Example:

e := NewEngine()
e.Plural("cat") // returns "cats"

func No

func No(word string, count int) string

No returns a count and noun phrase in English, using "no" for zero counts.

The function handles pluralization automatically:

  • For count 0 with classicalZero=false (default): returns "no" + plural form
  • For count 0 with classicalZero=true: returns "no" + singular form
  • For count 1: returns "1" + singular form
  • For count > 1: returns count + plural form

Examples:

  • No("error", 0) returns "no errors" (default)
  • No("error", 1) returns "1 error"
  • No("error", 2) returns "2 errors"
  • No("child", 0) returns "no children" (default)
  • No("child", 1) returns "1 child"
  • No("child", 3) returns "3 children"

With ClassicalZero(true):

  • No("error", 0) returns "no error"
  • No("child", 0) returns "no child"

func Num

func Num(n ...int) int

Num stores and retrieves a default count for number-related operations.

When called with a positive integer, it stores that value as the default count and returns it. When called with 0 or no arguments, it clears the default count and returns 0.

Examples:

  • Num(5) stores 5 as default count, returns 5
  • Num(0) clears the default count, returns 0
  • Num() clears the default count, returns 0

func NumberToWords

func NumberToWords(n int) string

NumberToWords converts an integer to its English word representation.

Examples:

  • NumberToWords(0) returns "zero"
  • NumberToWords(1) returns "one"
  • NumberToWords(42) returns "forty-two"
  • NumberToWords(100) returns "one hundred"
  • NumberToWords(1000) returns "one thousand"
  • NumberToWords(-5) returns "negative five"

func NumberToWordsFloat

func NumberToWordsFloat(f float64) string

NumberToWordsFloat converts a floating-point number to its English word representation.

The integer part is converted using NumberToWords, followed by "point", then each digit after the decimal point is converted individually.

Examples:

  • NumberToWordsFloat(3.14) returns "three point one four"
  • NumberToWordsFloat(0.5) returns "zero point five"
  • NumberToWordsFloat(-2.718) returns "negative two point seven one eight"

func NumberToWordsFloatWithDecimal

func NumberToWordsFloatWithDecimal(f float64, decimal string) string

NumberToWordsFloatWithDecimal converts a floating-point number to its English word representation using a custom word for the decimal point.

The integer part is converted using NumberToWords, followed by the specified decimal word, then each digit after the decimal point is converted individually.

Examples:

  • NumberToWordsFloatWithDecimal(3.14, "point") returns "three point one four"
  • NumberToWordsFloatWithDecimal(3.14, "dot") returns "three dot one four"
  • NumberToWordsFloatWithDecimal(3.14, "and") returns "three and one four"

func NumberToWordsGrouped

func NumberToWordsGrouped(n int, groupSize int) string

NumberToWordsGrouped converts an integer to English words by splitting it into groups of the specified size and converting each group independently.

This is useful for reading phone numbers, credit card numbers, and other digit sequences where each group should be pronounced as a separate number.

The number is split from right to left, so the leftmost group may have fewer digits than the specified group size.

Examples:

  • NumberToWordsGrouped(1234, 2) returns "twelve thirty-four"
  • NumberToWordsGrouped(123456, 2) returns "twelve thirty-four fifty-six"
  • NumberToWordsGrouped(1234, 3) returns "one two hundred thirty-four"
  • NumberToWordsGrouped(1234567890, 3) returns "one two hundred thirty-four five hundred sixty-seven eight hundred ninety"
  • NumberToWordsGrouped(0, 2) returns "zero"
  • NumberToWordsGrouped(-1234, 2) returns "negative twelve thirty-four"

func NumberToWordsThreshold

func NumberToWordsThreshold(n int, threshold int) string

NumberToWordsThreshold converts an integer to its English word representation only if the number is below the specified threshold. If the number is greater than or equal to the threshold, it returns the number as a string.

This is useful for making text more readable by spelling out small numbers while keeping larger numbers in digit form.

Examples:

  • NumberToWordsThreshold(5, 10) returns "five" (5 < 10, convert to words)
  • NumberToWordsThreshold(15, 10) returns "15" (15 >= 10, return as string)
  • NumberToWordsThreshold(100, 100) returns "100" (100 >= 100, return as string)
  • NumberToWordsThreshold(-3, 10) returns "negative three" (-3 < 10, convert to words)

func NumberToWordsWithAnd

func NumberToWordsWithAnd(n int) string

NumberToWordsWithAnd converts an integer to its English word representation using British English style with "and" before the final part.

This style inserts "and" after hundreds when followed by tens or ones, and after thousands/millions/billions when followed by a number less than 100.

Examples:

  • NumberToWordsWithAnd(101) returns "one hundred and one"
  • NumberToWordsWithAnd(121) returns "one hundred and twenty-one"
  • NumberToWordsWithAnd(1001) returns "one thousand and one"
  • NumberToWordsWithAnd(1101) returns "one thousand one hundred and one"
  • NumberToWordsWithAnd(-101) returns "negative one hundred and one"

func Ordinal

func Ordinal(n int) string

Ordinal converts an integer to its ordinal string representation.

Examples:

  • Ordinal(1) returns "1st"
  • Ordinal(2) returns "2nd"
  • Ordinal(3) returns "3rd"
  • Ordinal(11) returns "11th"
  • Ordinal(21) returns "21st"
  • Ordinal(-1) returns "-1st"

func OrdinalSuffix

func OrdinalSuffix(n int) string

OrdinalSuffix returns the ordinal suffix for a number ("st", "nd", "rd", or "th").

This is useful when you need just the suffix without the number.

Examples:

  • OrdinalSuffix(1) returns "st"
  • OrdinalSuffix(2) returns "nd"
  • OrdinalSuffix(3) returns "rd"
  • OrdinalSuffix(4) returns "th"
  • OrdinalSuffix(11) returns "th" (special case for teens)
  • OrdinalSuffix(21) returns "st"
  • OrdinalSuffix(-1) returns "st" (uses absolute value)

func OrdinalToCardinal

func OrdinalToCardinal(s string) string

OrdinalToCardinal converts an ordinal to its cardinal form.

If the input is a numeric ordinal (e.g., "1st"), it returns the number (e.g., "1"). If the input is a word ordinal (e.g., "first"), it returns the cardinal word (e.g., "one"). If the input is not an ordinal, it is returned unchanged.

The function preserves the case pattern of the input:

  • "first" → "one"
  • "First" → "One"
  • "FIRST" → "ONE"
  • "Twenty-First" → "Twenty-One"

Examples:

  • OrdinalToCardinal("1st") returns "1"
  • OrdinalToCardinal("first") returns "one"
  • OrdinalToCardinal("twenty-first") returns "twenty-one"
  • OrdinalToCardinal("one") returns "one" (unchanged, not an ordinal)

func OrdinalWord

func OrdinalWord(n int) string

OrdinalWord converts an integer to its ordinal word representation.

Examples:

  • OrdinalWord(1) returns "first"
  • OrdinalWord(2) returns "second"
  • OrdinalWord(11) returns "eleventh"
  • OrdinalWord(21) returns "twenty-first"
  • OrdinalWord(100) returns "one hundredth"
  • OrdinalWord(101) returns "one hundred first"
  • OrdinalWord(-1) returns "negative first"

func Parameterize

func Parameterize(word string) string

Parameterize converts a string to a URL-safe slug using dashes as separators.

This function is provided for compatibility with github.com/go-openapi/inflect and Rails ActiveSupport.

Examples:

Parameterize("Hello World!")     // "hello-world"
Parameterize("Hello, World!")    // "hello-world"
Parameterize("  Multiple   Spaces  ") // "multiple-spaces"

func ParameterizeJoin

func ParameterizeJoin(word string, sep string) string

ParameterizeJoin converts a string to a URL-safe slug using a custom separator.

This function is provided for compatibility with github.com/go-openapi/inflect and Rails ActiveSupport.

Examples:

ParameterizeJoin("Hello World!", "_") // "hello_world"
ParameterizeJoin("Hello World!", "-") // "hello-world"

func PascalCase

func PascalCase(s string) string

PascalCase converts a string to PascalCase.

It handles snake_case, kebab-case, and mixed inputs. Each word's first letter is capitalized, with no separators.

Examples:

  • PascalCase("hello_world") returns "HelloWorld"
  • PascalCase("hello-world") returns "HelloWorld"
  • PascalCase("hello world") returns "HelloWorld"
  • PascalCase("HTTP_SERVER") returns "HttpServer"

func PastParticiple

func PastParticiple(verb string) string

PastParticiple converts a verb to its past participle form.

Examples:

  • PastParticiple("walk") returns "walked" (regular -ed)
  • PastParticiple("stop") returns "stopped" (double consonant)
  • PastParticiple("try") returns "tried" (y -> ied)
  • PastParticiple("go") returns "gone" (irregular)
  • PastParticiple("take") returns "taken" (irregular)
  • PastParticiple("run") returns "run" (unchanged irregular)

func PastTense

func PastTense(verb string) string

PastTense returns the simple past tense form of an English verb.

Examples:

  • PastTense("walk") returns "walked"
  • PastTense("go") returns "went"
  • PastTense("try") returns "tried"
  • PastTense("stop") returns "stopped"

func Plural

func Plural(word string) string

Plural returns the plural form of an English noun.

Examples:

  • Plural("cat") returns "cats"
  • Plural("box") returns "boxes"
  • Plural("child") returns "children"
  • Plural("sheep") returns "sheep"

func PluralAdj

func PluralAdj(word string, count ...int) string

PluralAdj returns the plural form of an English adjective.

This function handles:

  • Demonstrative adjectives: "this" -> "these", "that" -> "those"
  • Indefinite articles: "a" -> "some", "an" -> "some"
  • Possessive adjectives: "my" -> "our", "his"/"her"/"its" -> "their"

If count is provided and equals 1 or -1, returns the singular form. If count is not 1, returns the plural form. If no count is provided, returns the plural form.

Examples:

PluralAdj("this") returns "these"
PluralAdj("that") returns "those"
PluralAdj("a") returns "some"
PluralAdj("an") returns "some"
PluralAdj("my") returns "our"
PluralAdj("this", 1) returns "this"
PluralAdj("this", 2) returns "these"

func PluralNoun

func PluralNoun(word string, count ...int) string

PluralNoun returns the plural form of an English noun or pronoun.

This function handles:

  • Pronouns in nominative case: "I" -> "we", "he"/"she"/"it" -> "they"
  • Pronouns in accusative case: "me" -> "us", "him"/"her" -> "them"
  • Possessive pronouns: "my" -> "our", "mine" -> "ours", "his"/"her"/"its" -> "their"
  • Reflexive pronouns: "myself" -> "ourselves", "himself"/"herself"/"itself" -> "themselves"
  • Regular nouns: defers to Plural()

If count is provided and equals 1 or -1, returns the singular form. If count is not 1, returns the plural form. If no count is provided, returns the plural form.

Examples:

PluralNoun("I") returns "we"
PluralNoun("me") returns "us"
PluralNoun("my") returns "our"
PluralNoun("cat") returns "cats"
PluralNoun("cat", 1) returns "cat"
PluralNoun("cat", 2) returns "cats"

func PluralVerb

func PluralVerb(word string, count ...int) string

PluralVerb returns the plural form of an English verb.

This function handles:

  • Auxiliary verbs: "is" -> "are", "was" -> "were", "has" -> "have"
  • Contractions: "isn't" -> "aren't", "doesn't" -> "don't", "hasn't" -> "haven't"
  • Modal verbs (unchanged): "can", "could", "may", "might", "must", "shall", "should", "will", "would"
  • Regular verbs in third person singular: removes -s/-es suffix

If count is provided and equals 1 or -1, returns the singular form. If count is not 1, returns the plural form. If no count is provided, returns the plural form.

Examples:

PluralVerb("is") returns "are"
PluralVerb("was") returns "were"
PluralVerb("has") returns "have"
PluralVerb("doesn't") returns "don't"
PluralVerb("runs") returns "run"
PluralVerb("is", 1) returns "is"
PluralVerb("is", 2) returns "are"

func Pluralize

func Pluralize(word string) string

Pluralize is an alias for Plural, provided for compatibility with github.com/go-openapi/inflect.

Example:

Pluralize("cat") // returns "cats"

func Possessive

func Possessive(word string) string

Possessive returns the possessive form of an English noun.

Rules applied:

  • Singular nouns: add 's (cat → cat's)
  • Plural nouns ending in s: add only ' (cats → cats')
  • Plural nouns not ending in s: add 's (children → children's)
  • Singular nouns ending in s: add 's or ' based on PossessiveStyle setting
  • Words already in possessive form are returned unchanged

Examples:

  • Possessive("cat") returns "cat's"
  • Possessive("cats") returns "cats'"
  • Possessive("children") returns "children's"
  • Possessive("James") returns "James's" (with PossessiveModern)
  • Possessive("James") returns "James'" (with PossessiveTraditional)

func PossessiveStyle

func PossessiveStyle(style impl.PossessiveStyleType)

PossessiveStyle sets the style for forming possessives of words ending in s. Use PossessiveModern (default) for "James's" or PossessiveTraditional for "James'".

func PresentParticiple

func PresentParticiple(verb string) string

PresentParticiple converts a verb to its present participle (-ing) form.

Examples:

  • PresentParticiple("run") returns "running" (double consonant)
  • PresentParticiple("make") returns "making" (drop silent e)
  • PresentParticiple("play") returns "playing" (just add -ing)
  • PresentParticiple("die") returns "dying" (ie -> ying)
  • PresentParticiple("see") returns "seeing" (ee -> eeing)
  • PresentParticiple("panic") returns "panicking" (c -> ck)

func Reset

func Reset()

Reset restores the default Engine to its initial state. This clears all custom definitions and resets all options to defaults.

This is equivalent to calling defaultEngine.Reset() and affects all subsequent package-level function calls.

Example:

inflect.Classical(true)
inflect.DefNoun("foo", "foos")
inflect.Reset()
inflect.IsClassical() // returns false
inflect.Plural("foo") // returns "foos" (standard rule, custom removed)

func RomanToInt added in v2.1.0

func RomanToInt(s string) (int, error)

RomanToInt converts a Roman numeral string to its integer value.

The function accepts both uppercase and lowercase input. It validates the input and returns an error for malformed numerals.

Validation rules:

  • Only valid Roman numeral characters (I, V, X, L, C, D, M)
  • No more than 3 consecutive identical numerals (except M)
  • V, L, D cannot repeat
  • Valid subtractive combinations only (IV, IX, XL, XC, CD, CM)

Examples:

  • RomanToInt("XIV") returns (14, nil)
  • RomanToInt("MMXXV") returns (2025, nil)
  • RomanToInt("iv") returns (4, nil)
  • RomanToInt("IIII") returns (0, error)
  • RomanToInt("ABC") returns (0, error)

func Singular

func Singular(word string) string

Singular returns the singular form of an English noun.

Examples:

  • Singular("cats") returns "cat"
  • Singular("boxes") returns "box"
  • Singular("children") returns "child"
  • Singular("sheep") returns "sheep"

func SingularNoun

func SingularNoun(word string, count ...int) string

SingularNoun returns the singular form of an English noun or pronoun.

This function handles:

  • Pronouns in nominative case: "we" -> "I", "they" -> he/she/it/they (depends on gender)
  • Pronouns in accusative case: "us" -> "me", "them" -> him/her/it/them (depends on gender)
  • Possessive pronouns: "our" -> "my", "ours" -> "mine", "their" -> his/her/its/their
  • Reflexive pronouns: "ourselves" -> "myself", "themselves" -> himself/herself/itself/themself
  • Regular nouns: defers to Singular()

Third-person singular pronouns use the gender set by Gender():

  • Gender("m"): masculine - "they" -> "he"
  • Gender("f"): feminine - "they" -> "she"
  • Gender("n"): neuter - "they" -> "it"
  • Gender("t"): they (singular they) - "they" -> "they"

If count is provided and equals 1 or -1, returns the singular form. If count is not 1, returns the plural form. If no count is provided, returns the singular form.

Examples:

SingularNoun("we") returns "I"
SingularNoun("us") returns "me"
SingularNoun("our") returns "my"
SingularNoun("they") returns "it" (or he/she/they based on gender)
SingularNoun("cats") returns "cat"
SingularNoun("cats", 1) returns "cat"
SingularNoun("cats", 2) returns "cats"

func Singularize

func Singularize(word string) string

Singularize is an alias for Singular, provided for compatibility with github.com/go-openapi/inflect.

Example:

Singularize("cats") // returns "cat"

func SnakeCase

func SnakeCase(s string) string

SnakeCase is an alias for Underscore. It converts a string to snake_case.

Examples:

  • SnakeCase("HelloWorld") returns "hello_world"
  • SnakeCase("HTTPServer") returns "http_server"

func Superlative

func Superlative(adj string) string

Superlative returns the superlative form of an English adjective.

Examples:

  • Superlative("big") returns "biggest"
  • Superlative("happy") returns "happiest"
  • Superlative("beautiful") returns "most beautiful"
  • Superlative("good") returns "best"

func Tableize

func Tableize(word string) string

Tableize creates a table name from a type name. It underscores and pluralizes the word.

This function is provided for compatibility with github.com/go-openapi/inflect and Rails ActiveSupport.

Examples:

Tableize("Person")         // "people"
Tableize("RawScaledScorer") // "raw_scaled_scorers"
Tableize("MouseTrap")      // "mouse_traps"

func TitleCase

func TitleCase(s string) string

TitleCase is an alias for PascalCase. It converts a string to PascalCase (also known as TitleCase in some contexts).

Note: This is different from Titleize which preserves word separators.

Examples:

  • TitleCase("hello_world") returns "HelloWorld"
  • TitleCase("hello-world") returns "HelloWorld"

func Titleize

func Titleize(s string) string

Titleize converts a string to title case.

Each word's first letter is capitalized, rest are lowercased.

Examples:

  • Titleize("hello world") returns "Hello World"
  • Titleize("HELLO WORLD") returns "Hello World"
  • Titleize("hello-world") returns "Hello-World"

func Typeify

func Typeify(word string) string

Typeify converts a table name or plural word to a type name (singular, PascalCase).

This function is provided for compatibility with github.com/go-openapi/inflect and Rails ActiveSupport.

Examples:

Typeify("users")           // "User"
Typeify("raw_scaled_scorers") // "RawScaledScorer"
Typeify("people")          // "Person"

func UndefA

func UndefA(word string) bool

UndefA removes a custom "a" pattern.

Returns true if the pattern was removed, false if it didn't exist.

Examples:

DefA("ape")
An("ape") // returns "a ape"
UndefA("ape")
An("ape") // returns "an ape" (default rule)

func UndefAPattern

func UndefAPattern(pattern string) bool

UndefAPattern removes a regex pattern from the "a" patterns list.

The pattern string must match exactly as it was defined (before anchoring). Returns true if the pattern was found and removed, false otherwise.

Examples:

DefAPattern("euro.*")
An("european") // returns "a european"
UndefAPattern("euro.*")
An("european") // returns "an european" (default rule)

func UndefAdj

func UndefAdj(singular string) bool

UndefAdj removes a custom adjective pluralization rule.

NOTE: This is a placeholder stub for future implementation.

Returns true if the rule was removed, false if it didn't exist.

Examples:

DefAdj("big", "bigs")
UndefAdj("big") // returns true
UndefAdj("small") // returns false (not defined)

func UndefAn

func UndefAn(word string) bool

UndefAn removes a custom "an" pattern.

Returns true if the pattern was removed, false if it didn't exist.

Examples:

DefAn("hero")
An("hero") // returns "an hero"
UndefAn("hero")
An("hero") // returns "a hero" (default rule)

func UndefAnPattern

func UndefAnPattern(pattern string) bool

UndefAnPattern removes a regex pattern from the "an" patterns list.

The pattern string must match exactly as it was defined (before anchoring). Returns true if the pattern was found and removed, false otherwise.

Examples:

DefAnPattern("honor.*")
An("honorable") // returns "an honorable"
UndefAnPattern("honor.*")
An("honorable") // returns "a honorable" (default rule)

func UndefNoun

func UndefNoun(singular string) bool

UndefNoun removes a custom noun pluralization rule.

This removes only user-defined rules; it cannot remove built-in irregular plurals. To restore a built-in rule that was overwritten, use DefNounReset().

Returns true if the rule was removed, false if it didn't exist or was a built-in rule.

Examples:

DefNoun("foo", "foos")
Plural("foo") // returns "foos"
UndefNoun("foo")
Plural("foo") // returns "foos" (standard rule)

func UndefVerb

func UndefVerb(singular string) bool

UndefVerb removes a custom verb conjugation rule.

NOTE: This is a placeholder stub for future implementation.

Returns true if the rule was removed, false if it didn't exist.

Examples:

DefVerb("run", "runs")
UndefVerb("run") // returns true
UndefVerb("walk") // returns false (not defined)

func Underscore

func Underscore(s string) string

Underscore converts a string to snake_case.

It handles PascalCase, camelCase, kebab-case, and mixed inputs. Consecutive uppercase letters (like "HTTP") are kept together as one word.

Examples:

  • Underscore("HelloWorld") returns "hello_world"
  • Underscore("hello-world") returns "hello_world"
  • Underscore("HTTPServer") returns "http_server"
  • Underscore("getHTTPResponse") returns "get_http_response"
  • Underscore("already_snake") returns "already_snake"

func WordCount

func WordCount(text string) int

WordCount counts the number of words in a string.

Words are separated by whitespace. This is a simple word count that doesn't account for punctuation or special cases.

Examples:

  • WordCount("hello world") returns 2
  • WordCount(" one two three ") returns 3
  • WordCount("") returns 0
  • WordCount("single") returns 1

func WordToOrdinal

func WordToOrdinal(s string) string

WordToOrdinal converts a number word or numeric string to its ordinal form.

If the input is a numeric string (e.g., "42"), it returns the numeric ordinal (e.g., "42nd"). If the input is a word number (e.g., "forty-two"), it returns the word ordinal (e.g., "forty-second").

The function preserves the case pattern of the input:

  • "one" → "first"
  • "One" → "First"
  • "ONE" → "FIRST"
  • "Twenty-One" → "Twenty-First"

Examples:

  • WordToOrdinal("1") returns "1st"
  • WordToOrdinal("one") returns "first"
  • WordToOrdinal("twenty-one") returns "twenty-first"
  • WordToOrdinal("One") returns "First"
  • WordToOrdinal("TWENTY") returns "TWENTIETH"

Types

type Engine

type Engine = impl.Engine

Engine holds all mutable state for inflection operations. Use NewEngine() to create an instance with default settings. The Engine is safe for concurrent use; all methods are protected by a mutex.

Thread Safety Architecture

All mutable state is encapsulated within the Engine struct and protected by a sync.RWMutex. Package-level functions delegate to a defaultEngine instance, providing backward-compatible API while ensuring thread safety.

Mutable State (in Engine)

The following state is mutable and protected by Engine.mu:

  • Classical mode flags: classicalMode, classicalAll, classicalZero, classicalHerd, classicalNames, classicalAncient, classicalPersons
  • Custom noun mappings: irregularPlurals, singularIrregulars
  • Custom verb mappings: customVerbs, customVerbsReverse
  • Custom adjective mappings: customAdjs, customAdjsReverse
  • Custom article patterns: customAWords, customAnWords, customAPatterns, customAnPatterns
  • Gender setting: gender (for third-person pronoun singularization)
  • Possessive style: possessiveStyle (modern vs traditional)
  • Default number: defaultNum (for Num/GetNum)

Immutable State (package-level variables)

The following package-level variables are IMMUTABLE after initialization and are safe for concurrent read access without locking:

Lookup tables (never modified after init):

  • adjective.go: irregularComparatives, irregularSuperlatives, twoSyllableWithSuffix
  • adverb.go: irregularAdverbs, unchangedAdverbs
  • article.go: silentHWords, lowercaseAbbrevs
  • currency.go: currencies
  • number.go: onesCardinal, onesOrdinal, tensCardinal, tensOrdinal
  • ordinal.go: cardinalToOrdinal, ordinalToCardinalMap, ordinalWords
  • participle.go: doubleConsonantWords, irregularPastParticiples, knownParticiples
  • past_tense.go: irregularPastTense
  • plural.go: changeToVesWords, oExceptionWords, unchangedPlurals, herdAnimals, classicalLatinPlurals, defaultIrregularPlurals
  • possessive.go: irregularPluralNoS, singularEndsInS, commonNouns, truncatedNames, validShortA
  • pronouns.go: pronounNominativePlural, pronounAccusativePlural, pronounPossessivePlural, pronounReflexivePlural, allPronounsToPlural, pronoun*SingularByGender maps
  • singular.go: feWordBases
  • verbs.go: verbSingularToPlural, verbPluralToSingular, verbUnchanged, adjSingularToPlural, adjPluralToSingular, adjPluralToSingularByGender

Compiled regular expressions (immutable after compilation):

  • inflect_funcs.go: inflectFuncPattern
  • rails.go: notURLSafe, multiSep

Function lookup tables (immutable after init):

  • inflect_funcs.go: inflectFuncs

Default Engine

The package-level defaultEngine (in classical.go) is created at package initialization and used by all package-level functions. It is safe for concurrent use but modifications affect all callers globally. For isolated configurations, use NewEngine() to create separate instances.

type PossessiveStyleType

type PossessiveStyleType = impl.PossessiveStyleType

PossessiveStyleType represents the style for forming possessives of words ending in s.

Directories

Path Synopsis
internal
inflect
Package inflect provides English language inflection utilities.
Package inflect provides English language inflection utilities.

Jump to

Keyboard shortcuts

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