Skip to content

Instantly share code, notes, and snippets.

@MashinaMashina
Last active November 24, 2022 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MashinaMashina/a79f31e0ecc675a7e83075fafa85a6a1 to your computer and use it in GitHub Desktop.
Save MashinaMashina/a79f31e0ecc675a7e83075fafa85a6a1 to your computer and use it in GitHub Desktop.
Склонение числительных в golang с дженериками
type Number interface {
int | int8 | int16 | int32 | int64 | float32 | float64
}
// Declination - склонение слов.
// Пример: Declination(10, []string{"отзыв", "отзыва", "отзывов"})
// Слова пишутся для чисел 1, 2, 5 (1 отзыв, 2 отзыва, 5 отзывов)
func Declination[T Number](untypedInt T, titles []string) string {
if untypedInt < 0 {
untypedInt *= -1
}
number := uint(untypedInt)
cases := []int{2, 0, 1, 1, 1, 2}
var currentCase int
if number%100 > 4 && number%100 < 20 {
currentCase = 2
} else if number%10 < 5 {
currentCase = cases[number%10]
} else {
currentCase = cases[5]
}
return titles[currentCase]
}
@MashinaMashina
Copy link
Author

MashinaMashina commented Nov 24, 2022

https://go.dev/play/p/SqX5swU-R1q

Для простоты дробная часть просто отбрасывается и склонение идет по целому

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment