I'm trying a little of go programming language.
I'm a excited about the simplicity of the Go, but after playing with it I met some troubles.
1 . I know that Go doesn't support generics and inheritance. Is there any way to implement generic list?
I thinking about using:
type Any interface { }
but how can I check if the value is NULL.
I'm looking for some equivalent implementation to C
struct List {
List* tail;
void* head;
}
Or using algebraic datatype:
data List a = Nil | Cons a (List a)
2 . More advanced requirement would be to make some container for objects with a field of a particular type?
For example in Scala programming language I can type:
val List[Animal { type SuitableFood = Grass} ]
to get a List
of Animals
, which have a member type SuitableFood
which is Grass
It sound's like what you're trying to make is a linked list.
Here's an example of one included with golang:
http://golang.org/pkg/container/list/
And here's the source code:
http://golang.org/src/pkg/container/list/list.go
You can have a list of elements of type interface{}
. You can put any elements in, and when you get it out, you have to cast back to the type you want. This is like what you're doing void *
in your C example; and also like lists in Java before Generics, and in Objective-C, which doesn't have generics. All the containers in the Go library do this.
Without generics, there is no compile-time checking of the element types.
If you really wanted, you could implement run-time checks for element type, by using reflection to get the element types and checking them against the expected type. However, this is probably overkill.