In GO, rule is, methods can be defined only on named type and pointer to named type.
In C, below code, operations are defined on type(say List
),
typedef struct List List; //list.h
typedef struct {
bool(*canHandle)(ImplType);
List*(*createList)();
....
const void*(*listGetItem)(List*, const int);
.....
void(*swap)(List*, int, int);
}ListHandler;
typedef struct{
ListHandler *handler;
}ListRtti;
typedef struct List{
ListRtti rtti; // operation on type List
const void **array;
/* For housekeeping - Array enhancement/shrink */
int lastItemPosition;
int size;
}List;
In Java, operations are defined on type(say DList
),
public class DList {
private DListNode sentinel;
private int size;
public void addItem(Object item){
...
}
....
}
But in GO, code below, operations are allowed on named type and pointer to named type.
package main
type Cat struct {
}
func (c Cat) foo() {
// do stuff_
}
func (c *Cat) foo() {
// do stuff_
}
func main() {
}
Question:
1)
What is the idea of defining a method on a pointer to named type?
2)
How can a programmer know before hand, if foo()
has to work as pass by value/reference? Why GO compiler restrict defining method on both named typed and pointer to named type?
func(c *Cat)
but notfunc(c Cat)
.class X
. Same holds good for C