OneBite.Dev - Coding blog in a bite size

check if a string is a palindrome in Go

Code snippet on how to check if a string is a palindrome in Go

  package main
  
  import (
    "fmt"
    "strings"
  )
  
  func main() {
    str := "abba"
    rev := strings.Reverse(str)
    
    if str == rev {
        fmt.Println("String is a palindrome!")
    } else {
        fmt.Println("String is not a palindrome!")
    }
  }

This code allows us to check if a string is a palindrome or not. Initially, it imports necessary packages - fmt (for print output) and strings (for string manipulation). Following that, it defines a variable, “str”, and assigns a string value which is to be checked for being palindrome or not. Then it reverses the string value and stores it in another variable called “rev”. Finally, it compares the original string and the reversed string and gives us an output based on the comparison result. If the strings are equal, it prints “String is a palindrome!”, otherwise it prints “String is not a palindrome!“.

go