Created
November 30, 2017 08:53
-
-
Save chiliec/22e34af2d08a964fc1418908a19b0c15 to your computer and use it in GitHub Desktop.
Склонение числительных в 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
func declOfNum(number int, titles []string) string { | |
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] | |
} | |
titles := []string{"фотография", "фотографии", "фотографий"} | |
number := 1 | |
declOfNum(number, titles) |
С поддержкой отрицательных чисел:
https://go.dev/play/p/RZItGDnRHYo
func declOfNum(number int, titles []string) string {
if number < 0 {
number *= -1
}
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]
}
func main() {
titles := []string{"день", "дня", "дней"}
fmt.Println(1, declOfNum(1, titles))
fmt.Println(2, declOfNum(2, titles))
fmt.Println(5, declOfNum(5, titles))
fmt.Println(-1, declOfNum(-1, titles))
fmt.Println(-2, declOfNum(-2, titles))
fmt.Println(-5, declOfNum(-5, titles))
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
лучше использовать для
number
типuint
, т.к. при отрицательных значениях упадет