Skip to content

Instantly share code, notes, and snippets.

@inuoshios
Created December 31, 2021 17:23
Show Gist options
  • Save inuoshios/e945e24f75b85e8cfaf8f83fdb1e5f28 to your computer and use it in GitHub Desktop.
Save inuoshios/e945e24f75b85e8cfaf8f83fdb1e5f28 to your computer and use it in GitHub Desktop.
Type Casting in Golang -> integers to strings and strings to integers
package main
import (
"fmt"
"strconv" // This is used for conversion
)
func main() {
// Type Casting in Golang -> Converting strings to integers and integers into strings
// Convert an integer into string
var number = 123
var convToString = strconv.Itoa(number)
fmt.Printf("%s is of type %T \n", convToString, convToString) // Formatted string
// Convert a string to an integer
// Quick Question: What if the string you're trying to convert to an integer is "87gg" and not "87" -> It won't work 💀
var aString = "87gg"
convToInt, err := strconv.Atoi(aString) // the conversion takes place here.
if err != nil { // Checks if string can be converted to int
fmt.Println(err.Error()) // Returns an Error if it can't be converted
return
}
fmt.Printf("%d is of type %T \n", convToInt, convToInt) // Formatted string
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment