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
- Variables
- func A(word string) string
- func AddIrregular(singular string, plural string)
- func AddUncountable(words ...string)
- func Adverb(adj string) string
- func An(word string) string
- func Asciify(word string) string
- func CamelCase(s string) string
- func Camelize(word string) string
- func CamelizeDownFirst(word string) string
- func Capitalize(s string) string
- func Classical(enabled bool)
- func ClassicalAll(enabled bool)
- func ClassicalAncient(enabled bool)
- func ClassicalHerd(enabled bool)
- func ClassicalNames(enabled bool)
- func ClassicalPersons(enabled bool)
- func ClassicalZero(enabled bool)
- func Comparative(adj string) string
- func Compare(word1 string, word2 string) string
- func CompareAdjs(adj1 string, adj2 string) string
- func CompareNouns(noun1 string, noun2 string) string
- func CompareVerbs(verb1 string, verb2 string) string
- func CountSyllables(word string) int
- func CountingWord(n int) string
- func CountingWordThreshold(n int, threshold int) string
- func CountingWordWithOptions(n int, useThrice bool) string
- func CurrencyToWords(amount float64, currency string) string
- func Dasherize(s string) string
- func DefA(word string)
- func DefAPattern(pattern string) error
- func DefAReset()
- func DefAdj(singular string, plural string)
- func DefAdjReset()
- func DefAn(word string)
- func DefAnPattern(pattern string) error
- func DefNoun(singular string, plural string)
- func DefNounReset()
- func DefVerb(singular string, plural string)
- func DefVerbReset()
- func DefaultEngine() *impl.Engine
- func ForeignKey(word string) string
- func ForeignKeyCondensed(word string) string
- func FormatNumber(n int) string
- func FractionToWords(numerator int, denominator int) string
- func FractionToWordsWithFourths(numerator int, denominator int) string
- func FuncMap() template.FuncMap
- func FutureTense(verb string) string
- func Gender(g string)
- func GetGender() string
- func GetNum() int
- func GetPossessiveStyle() impl.PossessiveStyleType
- func Humanize(word string) string
- func IntToRoman(n int) string
- func IsClassical() bool
- func IsClassicalAll() bool
- func IsClassicalAncient() bool
- func IsClassicalHerd() bool
- func IsClassicalNames() bool
- func IsClassicalPersons() bool
- func IsClassicalZero() bool
- func IsOrdinal(s string) bool
- func IsParticiple(word string) bool
- func IsPlural(word string) bool
- func IsSingular(word string) bool
- func Join(words []string) string
- func JoinNoOxford(words []string) string
- func JoinNoOxfordWithConj(words []string, conj string) string
- func JoinWithAutoSep(words []string, conj string) string
- func JoinWithConj(words []string, conj string) string
- func JoinWithFinalSep(words []string, conj string, sep string, finalSep string) string
- func JoinWithSep(words []string, conj string, sep string) string
- func KebabCase(s string) string
- func NewEngine() *impl.Engine
- func No(word string, count int) string
- func Num(n ...int) int
- func NumberToWords(n int) string
- func NumberToWordsFloat(f float64) string
- func NumberToWordsFloatWithDecimal(f float64, decimal string) string
- func NumberToWordsGrouped(n int, groupSize int) string
- func NumberToWordsThreshold(n int, threshold int) string
- func NumberToWordsWithAnd(n int) string
- func Ordinal(n int) string
- func OrdinalSuffix(n int) string
- func OrdinalToCardinal(s string) string
- func OrdinalWord(n int) string
- func Parameterize(word string) string
- func ParameterizeJoin(word string, sep string) string
- func PascalCase(s string) string
- func PastParticiple(verb string) string
- func PastTense(verb string) string
- func Plural(word string) string
- func PluralAdj(word string, count ...int) string
- func PluralNoun(word string, count ...int) string
- func PluralVerb(word string, count ...int) string
- func Pluralize(word string) string
- func Possessive(word string) string
- func PossessiveStyle(style impl.PossessiveStyleType)
- func PresentParticiple(verb string) string
- func Reset()
- func RomanToInt(s string) (int, error)
- func Singular(word string) string
- func SingularNoun(word string, count ...int) string
- func Singularize(word string) string
- func SnakeCase(s string) string
- func Superlative(adj string) string
- func Tableize(word string) string
- func TitleCase(s string) string
- func Titleize(s string) string
- func Typeify(word string) string
- func UndefA(word string) bool
- func UndefAPattern(pattern string) bool
- func UndefAdj(singular string) bool
- func UndefAn(word string) bool
- func UndefAnPattern(pattern string) bool
- func UndefNoun(singular string) bool
- func UndefVerb(singular string) bool
- func Underscore(s string) string
- func WordCount(text string) int
- func WordToOrdinal(s string) string
- type Engine
- type PossessiveStyleType
Constants ¶
const PossessiveModern = impl.PossessiveModern
const PossessiveTraditional = impl.PossessiveTraditional
Variables ¶
var ErrInvalidRoman = impl.ErrInvalidRoman
ErrInvalidRoman is returned when a Roman numeral string is malformed.
Functions ¶
func AddIrregular ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Camelize is an alias for PascalCase, provided for compatibility with github.com/go-openapi/inflect.
Example:
Camelize("hello_world") // returns "HelloWorld"
func CamelizeDownFirst ¶
CamelizeDownFirst is an alias for CamelCase, provided for compatibility with github.com/go-openapi/inflect.
Example:
CamelizeDownFirst("hello_world") // returns "helloWorld"
func Capitalize ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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):
- Exact word matches (DefA)
- Exact word matches (DefAn)
- Regex patterns (DefAPattern)
- Regex patterns (DefAnPattern)
- 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 ¶
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 ¶
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):
- Exact word matches (DefA)
- Exact word matches (DefAn)
- Regex patterns (DefAPattern)
- Regex patterns (DefAnPattern)
- 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Pluralize is an alias for Plural, provided for compatibility with github.com/go-openapi/inflect.
Example:
Pluralize("cat") // returns "cats"
func Possessive ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
Singularize is an alias for Singular, provided for compatibility with github.com/go-openapi/inflect.
Example:
Singularize("cats") // returns "cat"
func SnakeCase ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.