Go R1 Day 28

progress

  • Solved [Hamming Distance] on exercism.io
  • Simple problem, but reminded me of how to use string split.
1
2
3
4
5
6
7
8
9
diffCount := 0
aString := strings.Split(a, "")
bString := strings.Split(b, "")

for i, x := range aString {
  if x != bString[i] {
    diffCount++
  }
}
  • Reviewed other solutions, and found my first attempt to split the string wasn’t necessary. Looks like I can just iterate on the string directly. I skipped this as it failed the first time. The error is: invalid operation: x != b[i] (mismatched types rune and byte).

This threw me for a loop initially, as I’m familar with .NET char datatype.

Golang doesn’t have a char data type. It uses byte and rune to represent character values. The byte data type represents ASCII characters and the rune data type represents a more broader set of Unicode characters that are encoded in UTF-8 format. Go Data Types

Explictly casting the data types solved the error. This would be flexibly for UTF8 special characters.

1
2
3
4
5
for i, x := range a {
  if rune(x) != rune(b[i]) {
    diffCount++
  }
}

With this simple test case, it’s it’s subjective if I’d need rune instead of just the plain ascii byte, so I finalized my solution with byte(x) instead.

1
2
3
4
5
for i, x := range a {
  if byte(x) != byte(b[i]) {
    diffCount++
  }
}