News for hackers. Stuff that matters.
Re:Leaving Go by Donch on Monday April 28, 2014 @01:02PM (#7661239)
The example could have been simplified:

  func abs(x Top) Top {
	switch v := x.(type) {
	case int32:
		if v < 0 {
			return -v
		}
	case int64:
		if v < 0 {
			return -v
		}
	case float32:
		if v < 0 {
			return -v
		}
	case float64:
		if v < 0 {
			return -v
		}
	}
	return v
  }
Re:Leaving Go by maxk42 on Monday April 28, 2014 @03:28PM (#7662310)
This doesn't work, but if it did you could simplify the switch statement to:

    switch v:= x.(type) {
    case int32, int64, float32, float64:
        if v < 0 {
            return -v
        }
    }
Go has some neat improvements to the switch statement: http://golang.org/doc/effective_go.html#switch
Re:Leaving Go by bsdetector on Monday April 28, 2014 @02:05PM (#7661753)
This isn't simpler, it's smaller. In fact it's more complicated, since instead of 4 completely separate cases you have 4 half-cases and a default.

For instance, pass a positive int16 and you get the right answer, but pass a negative int16 and you get a useable but wrong answer instead of nil from the original.

Re:Leaving Go by Donch on Monday April 28, 2014 @02:20PM (#7661882)
It was an example of a language feature, that is short variable declarations in type switches, which avoid repetitive casting. The example below has the default clause which handles unknown types. I suppose the point is that you'd never actually do any of this because the method is disgusting.

Thanks for the downvote :-)

Re:Leaving Go by bunkat on Monday April 28, 2014 @01:15PM (#7661352)
This code doesn't actually compile. You can't assign v to x.(type) like that.
Re:Leaving Go by jerf on Monday April 28, 2014 @01:37PM (#7661547)
Are you sure? http://play.golang.org/p/dJC328-rh8

I did have to put "return x" as the last statement, though, not return v. And I'm not sure I'm happy about an "abs" that happily returns a string if fed a string, but, well, that's Go.

Relevant bit of the spec: http://golang.org/ref/spec#Type_switches

Re:Leaving Go by Donch on Monday April 28, 2014 @01:44PM (#7661615)
It's horrible method with a horrible signature, that I didn't test :-)

But the short variable declaration in the type switch does indeed save the casts the OP was complaining about.

Even more correct and horrible: http://play.golang.org/p/ZMQKQhuUQT

Re:Leaving Go by bunkat on Monday April 28, 2014 @02:34PM (#7661966)
Yes, the return statement was what I was referring to. You can't use a type switch to do some sort of an implicit conversion that exists outside of the switch statement.