Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
44: String Manipulation with strings and strconv
If you're coming from Python, JavaScript, or even C#, you've probably already tried to do something like int("42") or String(123) in Go. I've seen it happen a dozen times in code reviews. You'll hit a compiler error that looks something like cannot convert "42" (type string) to type int, and it feels frustrating because, in your head, it's a simple type cast.
Stop trying to cast strings to integers
Here is the concrete reason why that doesn't work: in Go, a string is a read-only slice of bytes. An integer is a numeric value. They aren't just different "views" of the same data; they are entirely different memory layouts. You can't "cast" a sequence of characters into a number because the computer has to actually parse those characters and calculate the resulting numeric value. That's a logic operation, not a type conversion.
// This will fail to compile
age := "25"
numericAge := int(age) // ERROR: cannot convert age (type string) to type int
To do this, you need a tool that can read the string and do the math for you. That's where strconv comes in.
The strings package is for text, not types
One of the most common points of confusion I see is learners looking for conversion functions inside the strings package. Just remember: if you are changing the content of the text (trimming whitespace, replacing a word, splitting a sentence), use strings. If you are changing the type of the data (string to int, float to string), use strconv.
Let's look at the strings package first. I rarely use basic concatenation with + for complex logic because it's inefficient. Instead, I rely on functions like ReplaceAll and Split. For instance, imagine you're cleaning up a messy user-submitted tag list:
import "strings"
input := " golang, software-eng, backend "
// First, we trim the surrounding whitespace
trimmed := strings.TrimSpace(input)
// Then we split by the comma
tags := strings.Split(trimmed, ",")
for _, tag := range tags {
// Clean up each individual tag
cleanTag := strings.TrimSpace(tag)
fmt.Println("Processed tag:", cleanTag)
}
I personally find strings.Contains and strings.HasPrefix to be the most useful for basic routing or filtering logic. They are readable and performant.
Navigating the strconv conversion maze
Now, let's handle the actual conversion. The strconv package names can be a bit cryptic at first—Atoi and Itoa are the big ones. Atoi stands for "ASCII to Integer," and Itoa is "Integer to ASCII."
The most important thing to remember here is that conversions can fail. If a user passes the string "twenty-five" into Atoi, your program shouldn't just crash; it needs to handle that error.
import (
"fmt"
"strconv"
)
func main() {
val := "100"
// Atoi returns two values: the result and an error
i, err := strconv.Atoi(val)
if err != nil {
fmt.Println("That's not a valid number!")
return
}
fmt.Printf("The number is %d\n", i)
// To go back to a string, Itoa is simpler because it can't fail
s := strconv.Itoa(i)
fmt.Printf("Back to string: %s\n", s)
}
If you're dealing with decimals, you'll want strconv.ParseFloat. It's a bit more verbose because you have to specify the bit size (usually 64), but it gives you the precision you need for financial or scientific data.
📋 Practical Task
Exercise: Building a CSV Configuration Parser
In this exercise, you will write a small program that parses a configuration string. You'll receive a string representing a user's session data in the format: "username:gopher123,level:42,score:98.5".
Your goals:
- Use the
stringspackage to split the configuration string into individual key-value pairs. - Use the
stringspackage again to separate the key (e.g., "level") from the value (e.g., "42"). - Use the
strconvpackage to convert thelevelto anintand thescoreto afloat64. - Print the final results as typed variables.
Requirements:
- You must handle the error returned by
strconvfunctions. If a value cannot be converted, print an error message like"Invalid value for level". - Ensure that any accidental whitespace around the keys or values is trimmed.
There are no comments for now.