`SWIG/Examples/go/reference/`

## C++ Reference Handling

This example tests SWIG's handling of C++ references. A reference in C++ is much like a pointer. Go represents C++ classes as pointers which are stored in interface values. Therefore, a reference to a class in C++ simply becomes an object of the class type in Go. For types which are not classes, a reference in C++ is represented as a pointer in Go.

## Some examples

References are most commonly used as function parameters. For example, you might have a function like this:

>     Vector addv(const Vector &a, const Vector &b) {
>        Vector result;
>        result.x = a.x + b.x;
>        result.y = a.y + b.y;
>        result.z = a.z + b.z;
>        return result;
>     }

In these cases, SWIG transforms everything into a pointer and creates a wrapper that looks like this in C++.

>     Vector wrap_addv(Vector *a, Vector *b);

or like this in Go:

>     func Addv(arg1 Vector, arg2 Vector) Vector

Occasionally, a reference is used as a return value of a function when the return result is to be used as an lvalue in an expression. The prototypical example is an operator like this:

>     Vector &operator[](int index);

or a method:

>     Vector &get(int index);

For functions returning references, a wrapper like this is created:

>     Vector *wrap_Object_get(Object *self, int index) {
>         Vector &result = self->get(index);
>         return &result;
>     }

The following header file contains some class definitions with some operators and use of references.

## SWIG Interface

SWIG does NOT support overloaded operators so it can not directly build an interface to the classes in the above file. However, a number of workarounds can be made. For example, an overloaded operator can be stuck behind a function call such as the `addv` function above. Array access can be handled with a pair of set/get functions like this:

>     class VectorArray {
>     public:
>      ...
>        %addmethods {
>         Vector &get(int index) {
>           return (*self)[index];
>         }
>         void set(int index, Vector &a) {
>           (*self)[index] = a;
>         }
>        }
>        ...
>     }

Click here to see a SWIG interface file with these additions.

## Sample Go program

Click here to see a Go program that manipulates some C++ references.

## Notes:

- C++ references primarily provide notational convenience for C++ source code. However, Go only supports the 'x.a' notation so it doesn't much matter.

- When a program returns a reference, a pointer is returned. Unlike return by value, memory is not allocated to hold the return result.

- SWIG has particular trouble handling various combinations of references and pointers. This is side effect of an old parsing scheme and type representation that will be replaced in future versions.