we all know that one complain about go is the lack of *generics*.
However in `real life`, we don't miss them so often.
There are still cases we all like to have some kind of `generic` type.
To partially solve this problem we workaround using interfaces{} as input
parameters with type assertions, or we wrap a interface around a custom
type.
So I came up with a simple idea: *type family*
Type family should respect two laws:
1. Can't be allocated
2. Acts as real type
Basically given a *type family*:
type Unit (byte, rune)
type Units (
[]Unit,
string
)
Can be read as:
Unit is a *type *(family) that can be: *byte *or *rune*
Units is a *type *(family) that can be: *[]Unit* or *String*
In this way we can build a `generic function` like:
func insertAt(s Units, c Unit, i int) Units {
s = append(s, 0)
copy(s[i+1:], s[i:])
s[i] = c
return s
}
This reads as: Insert is a function that accepts a source *s *of type *Units,
*a *c *of type *Unit *and returns (the modified s): *Units.*
We can use this function in a pseudo generic way as:
a := "Hello World"
b := []byte(a)
c := []rune(a)
insertAt(a, "a", 10)
insertAt(b, '!', 10)
insertAt(c, '!', 10)
I think this is very easy to implement, we just need to update the grammar
and the parser to type check the family with an *OR* condition. Without
losing the precious type check of the compiler.
The solution keeps go-lang still very clean and simple and doesn't affect
the current code.
What do you think?
Cheers,
DAddYE
--
You received this message because you are subscribed to the Google Groups "golang-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/d/optout.