Created
May 30, 2021 13:13
-
-
Save spytheman/8e130adcac6736c380b432c7a60fdb5d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import term | |
| fn show(a []int, b []int) { | |
| padding := ' '.repeat(26) | |
| eprintln(padding + | |
| 'a.cap: $a.cap | a.len: $a.len ${a:-20} | b.cap: $b.cap | .len: $b.len ${b:-20}\n') | |
| } | |
| fn explain(code string, msg string) { | |
| padding := ' '.repeat(25 - code.len) | |
| eprintln(term.yellow(term.bold(code)) + '$padding // ' + term.gray(msg)) | |
| } | |
| explain('mut a := [1, 2, 3, 4, 5]', '') | |
| explain('mut b := a[1..3]', '> `a` and `b` both use the same memory block; `a` can access all elements in the block, `b` - only some.') | |
| mut a := [1, 2, 3, 4, 5] | |
| mut b := a[1..3] | |
| show(a, b) | |
| explain('b[0] = 100', 'Since both `a` and `b` use both the same memory block, this changes what is in a[1] too.') | |
| b[0] = 100 | |
| show(a, b) | |
| explain('a.trim(1)', 'After trimming, the memory block still exists, and the elements are not changed. What is changed, is *only* a.len .') | |
| a.trim(1) | |
| show(a, b) | |
| // a = a[..1] | |
| explain('a[0] = 200', 'This still modifies a shared element, that is visible to *both* `a` and `b`.') | |
| a[0] = 200 | |
| show(a, b) | |
| explain('a << 300', 'A new element is added to `a`. `a` still has enough capacity => no reallocation, but `a.len` changes.') | |
| a << 300 | |
| show(a, b) | |
| explain('a[1] = 400', 'Change an element of `a`, but `b` still shares it (because there was no reallocation) => `b[0]` is now also 400.') | |
| a[1] = 400 | |
| show(a, b) | |
| explain('b[0] = 500', 'Change an element of `b`, so likewise, `a[1]` is now too 500.') | |
| b[0] = 500 | |
| show(a, b) | |
| explain('b << 600', 'Append 600 to `b` => b was at its capacity, so it needs to allocate new space.') | |
| explain(' ', 'NB: ==> `b` is now *independent*, and no longer shares elements with `a`.') | |
| b << 600 | |
| show(a, b) | |
| explain('a[1] = 700', 'change an element of a, but does nothing to `b` now.') | |
| a[1] = 700 | |
| show(a, b) | |
| explain('a << 800', 'Add an element to `a`, does not change `b`.') | |
| a << 800 | |
| show(a, b) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Something similar can be achieved with this program (the first part makes it possible for the second part to use a kind of DSL), with less repetitions in the code to be executed/commented/traced: