Exercises

Interfaces and max()

In the maximum exercise we created a max function that works on a slice ofintegers. The question now is to create a program that shows the maximum numberand that works for both integers and floats. Try to make your program asgeneric as possible, although that is quite difficult in this case.

Answer

The following program calculates a maximum. It is as generic as you can get withGo.

  1. package main
  2. import "fmt"
  3. func Less(l, r interface{}) bool { 1
  4. switch l.(type) {
  5. case int:
  6. if _, ok := r.(int); ok {
  7. return l.(int) < r.(int) 2
  8. }
  9. case float32:
  10. if _, ok := r.(float32); ok {
  11. return l.(float32) < r.(float32) 3
  12. }
  13. }
  14. return false
  15. }
  16. func main() {
  17. var a, b, c int = 5, 15, 0
  18. var x, y, z float32 = 5.4, 29.3, 0.0
  19. if c = a; Less(a, b) { 4
  20. c = b
  21. }
  22. if z = x; Less(x, y) { 4
  23. z = y
  24. }
  25. fmt.Println(c, z)
  26. }

We could have chosen to make the return type of this 1 function aninterface{}, but that would mean that a caller would always have to do a typeassertion to extract the actual type from the interface. At 2 we compare theparameters. All parameters are confirmed to be integers, so this is legit. Andat 3 we do the some for floats. At 4 we get the maximum value for a, band x and y.

Pointers and reflection

One of the last paragraphs in section has the following words:

The code on the right works OK and sets the member Nameto “Albert Einstein”. Of course this only works when you call Set()with a pointer argument.

Why is this the case?

Answer

When called with a non-pointer argument the variable is a copy (call-by-value).So you are doing the reflection voodoo on a copy. And thus you are _not_changing the original value, but only this copy.