DEV Community

Archit Agarwal
Archit Agarwal

Posted on β€’ Edited on

Know How Elements Are Referenced in Range Loops to Avoid Common Pitfalls in Go

Hey Dev.to community! πŸ‘‹

If you've ever worked with range loops in Golang, you might have encountered some subtle yet frustrating bugs. These often arise from how elements are referenced within the loop. As Go developers, understanding this behaviour is crucial for writing clean, bug-free code.

In my latest article, I dive into:

  • How range loops handle element referencing behind the scenes.
  • The common mistakes developers make (like unintended modifications).
  • Practical tips and code examples to avoid these pitfalls.

Here’s a sneak peek at one common issue:

func getAvatarUrl(characterId int) string{
    // Simulate getting URL
    return fmt.Sprintf("https://base-url/%d", characterId)
}
type CharacterInfo struct {
    id          int
    characterName string
    avatarUrl   string
}
charactersOfGOT := []CharacterInfo{
    {id: 1, characterName: "Jon Snow"},
    {id: 2, characterName: "Daenerys Targaryen"},
    {id: 3, characterName: "Arya Stark"},
    {id: 4, characterName: "Tyrion Lannister"},
}

for _, charInfo := range charactersOfGOT {
    charInfo.avatarUrl = getAvatarUrl(charInfo.id)
}

for _, charInfo := range charactersOfGOT {
    fmt.Printf("Id: %d Name: %s, avatar: %s\n", charInfo.id, charInfo.characterName, charInfo.avatarUrl)
}
Enter fullscreen mode Exit fullscreen mode

Why doesn’t this output what you expect? πŸ˜… If you've faced a similar challenge, this article will help you understand why!

πŸ‘‰ Read the full article here to learn how to avoid these traps and become a pro at handling range loops in Go.

I'd love to hear your thoughts and experiences with Go's range loops. Have you run into any weird behaviour, or do you have tips to share? Let’s discuss this in the comments! πŸ™Œ

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here β†’

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay