Skip to content

Commit

Permalink
Merge pull request #178 from lgxbslgx/ADD_EXAMPLE
Browse files Browse the repository at this point in the history
Add an example about operator overloading
  • Loading branch information
bobzhang authored Apr 10, 2024
2 parents 8e471ac + e411f69 commit bce8abd
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,38 @@ fn init {
}
```

Another example about `op_get` and `op_set`:

```rust
struct Coord {
mut x: Int
mut y: Int
} derive(Debug)

fn op_get(self: Coord, key: String) -> Int {
match key {
"x" => self.x
"y" => self.y
}
}

fn op_set(self: Coord, key: String, val: Int) -> Unit {
match key {
"x" => self.x = val
"y" => self.y = val
}
}

fn init {
let c = { x: 1, y: 2 }
debug(c)
debug(c["y"])
c["x"] = 23
debug(c)
debug(c["x"])
}
```

Currently, the following operators can be overloaded:

| operator name | method name |
Expand Down
32 changes: 32 additions & 0 deletions zh-docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,38 @@ fn init {
}
```

另一个例子(关于`op_get``op_set`):

```rust
struct Coord {
mut x: Int
mut y: Int
} derive(Debug)

fn op_get(self: Coord, key: String) -> Int {
match key {
"x" => self.x
"y" => self.y
}
}

fn op_set(self: Coord, key: String, val: Int) -> Unit {
match key {
"x" => self.x = val
"y" => self.y = val
}
}

fn init {
let c = { x: 1, y: 2 }
debug(c)
debug(c["y"])
c["x"] = 23
debug(c)
debug(c["x"])
}
```

目前,以下运算符可以被重载:

| 运算符名称 | 方法名 |
Expand Down

0 comments on commit bce8abd

Please sign in to comment.