jorts/examples/struct-functions.jt
2019-03-08 18:45:33 -03:00

60 lines
935 B
Text

import io
struct A {
int val1,
int val2
}
// self is injected and represents the struct A
// from the functions' definition
fn A:sum_fields() -> int {
self.val1 + self.val2
}
// type of sum_fields is:
// Func ([A] -> int)
// the mut keyword signals that self is a "reference"
// to self, instead of a copy
// however, what actually happens is that an instance of
// A is returned from the function implicitly
fn mut A:incr_both_fields() {
self.val1++
self.val2++
}
// and so, the type becomes:
// Func ([A] -> A)
fn mut A:incr_and_sum () {
self.val1++
self.val2++
self.val1 + self.val2
}
// type is:
// Func ([A] -> (A, int))
fn main () {
a := A{0, 0}
a.incr_both_fields()
/*
translates to:
a := incr_both_fields(a)
*/
sum := a.sum_fields()
io.puts(sum)
val = a.incr_and_sum()
/*
translates to:
a, val := incr_and_sum(a)
*/
}