The strconv package in Go provides functions to convert between strings and other data types, such as integers, floats, and booleans. This article will delve into using the strconv package for various conversions with examples.

Converting Strings to Integers

You can convert a string to an integer using the strconv.Atoi function. The input must be a valid integer string, or it will return an error.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "123"
    num, err := strconv.Atoi(str)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Converted Number:", num)
    }
}

Converting Integers to Strings

To convert an integer to a string, use strconv.Itoa. This is a straightforward conversion.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    num := 123
    str := strconv.Itoa(num)
    fmt.Println("Converted String:", str)
}

Parsing and Formatting Floats

For float to string conversion, use strconv.FormatFloat, specifying the precision and format.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    f := 123.456
    str := strconv.FormatFloat(f, 'f', 2, 64)
    fmt.Println("Formatted String:", str)
}

To convert a string back to a float, use strconv.ParseFloat:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "123.456"
    f, err := strconv.ParseFloat(str, 64)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Parsed Float:", f)
    }
}

Working with Booleans

Convert a boolean to a string using strconv.FormatBool, and from a string back to a boolean using strconv.ParseBool.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Format boolean to string
    b := true
    str := strconv.FormatBool(b)
    fmt.Println("Formatted String:", str)

    // Parse string to boolean
    strBool := "true"
    parsedBool, err := strconv.ParseBool(strBool)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Parsed Boolean:", parsedBool)
    }
}

Practical Usage and Error Handling

When using strconv for conversions, always handle potential errors especially when parsing strings that might not correctly convert to the desired type. The error messages provided by these functions can help diagnose issues quickly.