Sobes.tech
Junior

Is it possible to convert a string to an integer and an integer to a string?

sobes.tech AI

Answer from AI

Yes, it is possible.

Converting a string to an integer:

// Import the strconv package
import "strconv"

// Example string
str := "123"

// Convert string to int
// err will be nil if the conversion is successful
i, err := strconv.Atoi(str)
if err != nil {
	// Handle error if the string is not a valid number
	// fmt.Println("Conversion error:", err)
} else {
	// Now i contains the integer
	// fmt.Println("Converted number:", i)
}

Converting an integer to a string:

// Import the strconv package (if not already imported)
import "strconv"

// Example integer
num := 456

// Convert int to string
s := strconv.Itoa(num)

// Now s contains the string representation of the number
// fmt.Println("Converted string:", s)