Methods in Cilk

Cilk supports methods defined on struct types.

#include <cilk/cilk.h>
#include <stdio.h>

typedef struct {
    int width;
    int height;
} rect;

// This `area` function takes a pointer to rect as its first argument
int area(rect* r) {
    return r->width * r->height;
}

// Here's an example of a function that takes a rect by value
int perim(rect r) {
    return 2*r.width + 2*r.height;
}

int main() {
    rect r = {.width = 10, .height = 5};

    // Here we call the 2 functions defined for our struct
    printf("area: %d\n", area(&r));
    printf("perim: %d\n", perim(r));

    // Cilk doesn't have automatic conversion between values and pointers,
    // so we need to explicitly pass the address when calling `area`
    rect* rp = &r;
    printf("area: %d\n", area(rp));
    printf("perim: %d\n", perim(*rp));

    return 0;
}

In this Cilk version, we’ve translated the Go code to use C-style structs and functions. Cilk, being an extension of C, doesn’t have methods in the same way that Go does. Instead, we define functions that take the struct as their first parameter.

The area function takes a pointer to a rect, while perim takes a rect by value. This mirrors the receiver types in the original Go code.

In the main function, we create a rect and call our functions. Note that when calling area, we need to explicitly pass the address of the rect, while for perim we pass the rect directly.

When using a pointer to rect (rp), we need to explicitly dereference it when passing to perim, as Cilk doesn’t automatically handle this conversion like Go does.

To compile and run this Cilk program:

$ cilk++ methods.cilk -o methods
$ ./methods
area: 50
perim: 30
area: 50
perim: 30

While Cilk doesn’t have the concept of methods in the same way as Go, we can achieve similar functionality by using functions that take the struct as their first parameter. The main difference is that in Cilk (and C), we need to be more explicit about when we’re using pointers versus values.