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:
funcdistance(a,b[]byte)(distint,errerror){iflen(a)!=len(b){returndist,errors.New("length of provided strings is not equal")}fori:=0;i<len(a);i++{ifa[i]!=b[i]{dist++}}returndist,nil}
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
andb
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:
Thanks for the feedback, I updated the post with your solution.
You are welcome, and thanks a lot for including my answer!