Palindrome using generics in Go 1.18

palindrome function in go that can receive integer or string, utilize generics feature

Yuda Prasetiya
2 min readMar 24, 2022

--

This time I want to talk about my experience trying generics in go 1.18.
After readings a few articles and watch some videos about generics in Go 1.18, I’m interested in using it to create a palindrome checking function that can accept both strings and integers.

First I create a new project called palindrome, and a new package also called palindrome then create constrains called signedOrString that can receive signed (int, int8, int16, int32, and int64) or a string. Then create a function for checking it is palindrome or not.

It’s really nice feature I think, because we didn’t have to recreate function that do the same thing for each data type.

Then I want to upgrade the function to check palindrome directly from a word or number, not from slice. I tried using generics feature again, and got stumbled this time because when we input type string to the function we can use build in Split function to convert it to slice, whereas to convert type integer to slice we need to create our own function.

How we can differentiate the flow between string and Signed (integer) ?

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.

sliceInteger function to convert any signed (integer) value to slice integer is still a good practice to use generics, but for IsPalindrome function I think generics aren’t built to do that kind of jobs.
After that, we can call IsPalindrome function from main.go and check the input variable is palindrome or not.

Conclusion

Go 1.18 Generics is good for build a function who have exactly same flow regardless of whatever the input type, like the palindrome and sliceInteger function above.
For IsPalindrome function, at least other developer who call this function have the idea that it can only be input using string or signed (integer) type.

Don’t hesitate to comment if the code is not quite right, or if there are better approach to use go generics.
Thank you!

Full code available on https://github.com/yudaph/palindrome

Contact me

https://www.linkedin.com/in/yudaph/
https://github.com/yudaph

--

--