referencing and methods

This commit is contained in:
uan
2026-02-07 19:14:48 +01:00
parent 005828cec2
commit a3b978a09d
5 changed files with 269 additions and 39 deletions

View File

@@ -114,6 +114,40 @@ this is my string 17
---
### References
One's counterpart to C's pointers are references, which behave the exact same way.
The main difference is in how you reference/dereference a variable. We all know C's
referencing and dereferencing operators cause some confusion when first learning the language,
and to prevent this, One has designated `ref` and `deref` keywords that are meant to be used like
functions. Here's an example:
```
let x int = 6;
let ref_to_x ref(int) = ref(x);
let y int = deref(ref_to_x) # same as y = x
```
References to objects are again quite similar to C, with the only real difference being
the access to an object's members. in One, you an access members of an object or of a
reference to an object with the `.` notation. But you cannot access the members if the
reference nesting goes further. For example:
```
let u User = User{17} #user has age 17
print(u.age) # outputs 17
let ref_to_u ref(User) = ref(u)
print(ref_to_u.age) # outputs 17
let nested_ref ref(ref(User)) = ref(ref_to_u)
print(nested_ref.age) # not valid
```
Right now, in error messages, it's likely you will still find references marked as `*`s, such as `int*`
---
### Functions
Functions in One are very similar to what you see in languages such as go.
@@ -181,6 +215,22 @@ fn change_values(u User) {
---
### Methods
Defining a method is very similar to declaring a function. You just have to add the name
of the class between parentheses before the function name.
```
fn (User) age() void {
this.age++
}
```
as you can see, a variable called `this` is automatically declared in methods and is always
of type `ref` of the class, in this case `ref(User)`
---
### Print
Printing is still a work in progress feature, but right now you can print any primitive and non-primitive type.