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)
}
}