Created
April 21, 2012 19:41
-
-
Save alphazero/2439266 to your computer and use it in GitHub Desktop.
considering the maximal ugliness of not having generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Main concern for me is lack of generic functions | |
* it really isn't that bad. 2 (un-necessary given the information at hand) casts occur. | |
* - One category e.g. C#Add(..) entails casts by the provider, | |
* so that is not a huge concern. Note that the body of text typed remains effectively the same with or without generics. | |
* | |
* - other category e.g. call site casts remains. That is a concern that can't be addressed by the provider of the library, | |
* but I suppose it is ultimately partially the responsibility of the | |
package main | |
import "fmt" | |
// Ideally we would want to have generic definitions here | |
// and not Go's version of void* | |
// | |
type unaryOp func(interface{}) interface{} | |
type diadicOp func(interface{}, interface{}) interface{} | |
type C struct { | |
r, i int | |
} | |
// An impl. of a 'generic' function. | |
// Note that even if you had generics, you would need to write this function | |
// only diff is the .(C). casts. | |
// The fact that Go requires public functions to support interfaces naturally exacerbates the | |
// issue i.e. this can be called directly by someone with a C var (even if nil ...!). | |
func (a C) Add(b interface{}) interface{} { | |
r := a.r + b.(C).r | |
i := a.i + b.(C).i | |
return C{r, i} | |
} | |
// what is an issue. This is not type safe, but a wrapper (such as func GenBar below can address param in concerns.) | |
// | |
type GenFu interface { | |
Add(interface{}) interface{} | |
} | |
type Int int | |
func (b Int) Add(a interface{}) interface{} { | |
return b + a.(Int) | |
} | |
func main() { | |
c1 := C{55, 0} | |
c2 := C{0, 100} | |
cv := GenBar(c1, c2).(C) | |
fmt.Printf("what a cv:%d\n", cv) | |
i1 := Int(55) | |
i2 := Int(100) | |
iv := GenBar(i1, i2).(Int) | |
fmt.Printf("what an iv:%d\n", iv) | |
} | |
// expects GenFu implementations. This is type safe. | |
func GenBar(v1, v2 GenFu) interface{} { | |
r := v1.Add(v2) | |
fmt.Printf("%v + %v = %v\n",v1, v2, r) | |
return r | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment