Golang mis-conceptions and easy to make logical errors

Some mis-conceptions that might lead to logical errors in Golang Code.

1. Finding positing of a substring or character in a string after an offset.

I found a another mis-conception today about Slices in Go. Here is a code copied from “The little Go Book

In JavaScript, if we want to find the first space in a string (yes, slices work on strings too!) after the first five characters, we’d write:


haystack = "the spice must flow";

console.log(haystack.indexOf(" ", 5));

In Go, we leverage slices:


strings.Index(haystack[5:], " ")

Now the problem is these two things are not the same. You will get 9 in javascript and 4 in Go. Why is it 4 in Go? It’s because it’s creating a new slice first copying data from index 5 to end. So the new slice index starts at 0! You are actually getting the position in the new slice. How to write the correct code?



	position := strings.Index(haystack[5:], " ")

	if position < 0 {

		fmt.Println(-1)

	} else {

		fmt.Println(position + 5)

	}

2. using String interface for custom types

You can override how your custom type or struct be printed by defining a type function called String(), which indirectly implements the String interface. This works like toString() in Java. But one problem is it’s automatically called when you get to print your custom type using default Print functions in Go. So, you can easily fall into a loop like this:


type T struct {
    a int
    b float64
    c string
}

func (t *T) String() string {

    return fmt.Sprintf("MyString=%s", t); // Causes infinite loop. it calls t.String() first to get value.

}

fmt.Printf("%v\n", t) // it calls t.String() first and prints the return value.

Now why does it cause an infinite loop? It’s because when fmt.Springtf() gets a parameter of type T, it first calls .String() on the parameter. So, what should be the solution? Don’t pass a parameter of type T there. Pass anything else like string(t) or just pass fields of t.

…to be continued

Advertisements

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