Skip to Content
Course content

44: String Manipulation with strings and strconv

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 strings package to split the configuration string into individual key-value pairs.
  • Use the strings package again to separate the key (e.g., "level") from the value (e.g., "42").
  • Use the strconv package to convert the level to an int and the score to a float64.
  • Print the final results as typed variables.

Requirements:

  • You must handle the error returned by strconv functions. 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.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.