Склонение числительных в golang с дженериками
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://go.dev/play/p/SqX5swU-R1q
Для простоты дробная часть просто отбрасывается и склонение идет по целому