Sling Academy
Home/Golang/Converting Strings to and from Other Data Types in Go

Converting Strings to and from Other Data Types in Go

Last updated: November 24, 2024

In Go, interacting with strings and converting them to and from other data types is a common task in many applications. Understanding how to perform these conversions efficiently can help you write cleaner and more effective code. This article covers both basic and advanced techniques for string conversions in Go.

Basic Conversions

Let's start with some basic conversions from strings to other data types and vice versa.

String to Integer

To convert a string to an integer in Go, you can use the Atoi function from the strconv package.


package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "123"
    if num, err := strconv.Atoi(str); err == nil {
        fmt.Printf("Integer: %d\n", num)
    } else {
        fmt.Println("Error converting string to int", err)
    }
}

Integer to String

To convert an integer to a string in Go, you use the Itoa function from the strconv package.


package main

import (
    "fmt"
    "strconv"
)

func main() {
    num := 123
    str := strconv.Itoa(num)
    fmt.Printf("String: %s\n", str)
}

Intermediate Conversions

Next, we will explore conversions involving floating-point numbers and booleans.

String to Float

To convert a string to a float, use ParseFloat from the strconv package. You need to specify the precision, such as 32 or 64.


package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "123.45"
    if num, err := strconv.ParseFloat(str, 64); err == nil {
        fmt.Printf("Float: %f\n", num)
    } else {
        fmt.Println("Error converting string to float", err)
    }
}

Float to String

Convert a float to string using FormatFloat.


package main

import (
    "fmt"
    "strconv"
)

func main() {
    num := 123.45
    // 'f', -1, 64 means the format is 'f', no special precision; 64-bit representation
    str := strconv.FormatFloat(num, 'f', -1, 64)
    fmt.Printf("String: %s\n", str)
}

String to Boolean

You can convert a string to a boolean with ParseBool.


package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "true"
    if b, err := strconv.ParseBool(str); err == nil {
        fmt.Printf("Boolean: %t\n", b)
    } else {
        fmt.Println("Error converting string to boolean", err)
    }
}

Boolean to String

Convert a boolean to a string using the sprintf function or FormatBool.


package main

import (
    "fmt"
    "strconv"
)

func main() {
    b := true
    str := strconv.FormatBool(b)
    fmt.Printf("String: %s\n", str)
}

Advanced Conversions

For handling more complex data types like JSON or customizing parse formats, consider the following methods.

String to JSON

Using the encoding/json package, parse JSON strings into Go structs.


package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    jsonString := `{"Name":"John", "Age":30}`
    var person Person
    if err := json.Unmarshal([]byte(jsonString), &person); err == nil {
        fmt.Printf("Parsed JSON: %+v\n", person)
    } else {
        fmt.Println("Error parsing JSON", err)
    }
}

Struct to JSON String

Convert a Go struct to a JSON string using json.Marshal.


package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    person := Person{"Jane", 25}
    if jsonBytes, err := json.Marshal(person); err == nil {
        fmt.Printf("JSON String: %s\n", string(jsonBytes))
    } else {
        fmt.Println("Error generating JSON", err)
    }
}

Next Article: Formatting Strings in Go with `fmt.Sprintf`

Previous Article: String Comparison: Case Sensitivity and Equality in Go

Series: Working with Strings in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant