Skip to content

Ranging on Golang slices default values

December 4, 2013

Today I spent hours debugging what turned out to be a simple error. 

At one place my code was like this: 

// For a slice y which is has int as values

for x := range y {
xSet[int16(x)]=true
}

The problem was with the above it picks up just the indices into x. While writing code in a hurry I might have thought it will use the values. 

This problem gave me real hell. As the values are also very small (<=10)

Finally fixed this by ranging on array as: 

for _, x := range y {
xSet[int16(x)]=true
}

This change fixed it. But Boy, I spent 2-3 hours locating this error. As this is a large piece of intricate code, which I am migrating from Java. 

Perhaps should give feedback to Golang developers

 

Advertisements

From → Uncategorized

2 Comments
  1. i82much permalink

    It is definitely a departure from Python and Java. In python the values are what’s iterates; to get the index you need to use enumerate.

    I was fortunate to learn this lesson quickly and haven’t made this mistake yet. Doubt the go folks can do much for you about this

  2. Yes, you are right. After being bitten that time, I have been sure to remember that. Love Go BTW.

    PS: Sorry, saw your comment very very late.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: