Hey, fellow Gophers!
I just lately wrote an article diving right into a delicate however vital side of Go’s vary
loops: factor referencing. In the event you’ve ever discovered your self scratching your head over sudden behaviour when working with slices, maps, or different collections in a vary
loop, that is for you.
What’s Coated within the Article
- How
vary
handles components and pointers internally. - Widespread pitfalls builders encounter, like unintentional modifications or fallacious outputs.
- Suggestions and finest practices to keep away from these points whereas writing cleaner, bug-free Go code.
Right here’s a fast instance for example:
func getAvatarUrl(characterId int) string{
// Simulate getting URL
return fmt.Sprintf("https://base-url/%d", characterId)
}
sort 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 := vary charactersOfGOT {
charInfo.avatarUrl = getAvatarUrl(charInfo.id)
}
for _, charInfo := vary charactersOfGOT {
fmt.Printf("Id: %d Identify: %s, avatar: %sn", charInfo.id, charInfo.characterName, charInfo.avatarUrl)
}
If this code doesn’t behave the way in which you’d count on, you’re not alone! In my article, I clarify why this occurs and the way to write sturdy code that avoids such traps.
Learn the Full Article
Know How Parts Are Referenced in Vary Loops to Keep away from Widespread Pitfalls in Go
Let’s Talk about
Have you ever encountered related challenges with vary
loops? What methods have you ever used to keep away from these gotchas? I’d love to listen to your ideas, ideas, and experiences right here! Let’s collaborate and assist one another degree up in Go programming.