DEV Community

Discussion on: Go is my gateway drug

Collapse
 
ladydascalie profile image
Benjamin Cable • Edited

The Go implementation has some issues which I'd like to point out, and propose fixes for.

Firstly, you use len() on strings.
len returns the byte size rather than the character (or rune) length.

If that's your intent in the first place, then your function should accept a, b []byte directly and not bother with strings at all.

This removes the need for the type conversion inside the function.

Secondly, you're using a range over the byte slice for a, when a simple for loop would be simpler to read and write, given you've already asserted that a and b are of the same size.

Thirdly, named return parameters would enable you to write slightly more concise and obvious code.

Please also note that for local slices (that is to say, slices contained within the scope of a call-tree, and not defined globally), their length is cached, and calling len() therefore does not incur any overhead.

With that in mind, here is my proposed amended solution:

func distance(a, b []byte) (dist int, err error) {
    if len(a) != len(b) {
        return dist, errors.New("length of provided strings is not equal")
    }

    for i := 0; i < len(a); i++ {
        if a[i] != b[i] {
            dist++
        }
    }

    return dist, nil
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
peteraba profile image
Peter Aba

Thanks for the feedback, I updated the post with your solution.

Collapse
 
ladydascalie profile image
Benjamin Cable

You are welcome, and thanks a lot for including my answer!