visit
First I created a new project called palindrome, and a new package (also called palindrome). Then I created constrains called signedOrString that can receive signed (int, int8, int16, int32, and int64) or a string. Further, I created a function for checking whether it is palindrome or not.
type signedOrString interface{
constraints.Signed | string
}
func palindrome[input signedOrString](sliceInput []input) bool {
length := len(sliceInput)
for i:=0;i<length/2;i++{
if sliceInput[i] != sliceInput[length-1-i] {
return false
}
}
return true
}
I've come up with an idea to convert it to interface{} type, then separate the flow with switch function. Let's look at the code.
func IsPalindrome[input signedOrString](firstInput input) bool {
return func(toInterface interface{}) bool {
var sliceInt []int
switch newType := toInterface.(type){
case string:
return palindrome(strings.Split(newType, ""))
case int:
sliceInt = sliceInteger(newType)
case int8:
sliceInt = sliceInteger(newType)
case int16:
sliceInt = sliceInteger(newType)
case int32:
sliceInt = sliceInteger(newType)
case int64:
sliceInt = sliceInteger(newType)
}
return palindrome(sliceInt)
}(firstInput)
}
func sliceInteger[signed constraints.Signed](input signed) (slice []int) {
for input > 0 {
slice = append(slice, int(input%10))
input/=10
}
return
}
sliceInteger function to convert any signed (integer) value to slice integer is still a good practice to use generics, but for IsPalindromefunction I think generics aren’t built to do that kind of jobs.
After that, we can call IsPalindrome function from main.go and check whether the input variable is palindrome or not.
package main
import (
"fmt"
"palindrome/palindrome"
)
func main() {
fmt.Println(palindrome.IsPalindrome("AAAB")) // false
fmt.Println(palindrome.IsPalindrome("ABABA")) // true
fmt.Println(palindrome.IsPalindrome(10001)) // true
fmt.Println(palindrome.IsPalindrome(10110)) // false
}
Go 1.18 Generics is good for building a function that has exactly same flow regardless of whatever the input type, like the palindrome and sliceIntegerfunction above.
ForIsPalindrome function - other developers who call this function have the idea that it can only be input using string or signed (integer) type.
I hope some of you find this helpful. If you’re interested in seeing all the source code, you can find it on