That is basically what affine types are. Once the value is "consumed" it can't be used again.
In rust, this is expressed as passing an "owned" value to a function. Once you pass ownership, you can't use that value anymore.
And having used it in rust, I wish more languages had something like that.
Same. I'm at the point where I feel like copy-by-default semantics are one of the ancient original sins of programming languages. Single-ownership is so, so useful, and it's trivial to implement and not at all difficult to understand (especially compared to something like Rust's borrow checker).
Having explicit language to differentiate between pass by reference and pass by value avoids this confusion. It requires a little more thought from the programmer but it’s really minimal once you internalize it.
Rust takes this a step further with an explicit ownership and borrowing model. The compiler will refuse your code if you try to write something that that violates the borrow checker. This is endlessly frustrating to beginners but after adapting your mind to ownership safety you find yourself thinking in the same way in other languages.
I always found real-world JavaScript codebases frustrating because there was so much sharing that wasn’t entirely intentionally. It only got fixed when someone recognized a bug as a result.
For example:
# Original array
array = [1, 2, 3]
# Using map (non-destructive)
new_array = array.map { |x| x * 2 }
# new_array is [2, 4, 6]
# array is still [1, 2, 3] (unchanged)
# Using map! (destructive)
array.map! { |x| x * 2 }
# array is now [2, 4, 6] (modified in-place)
Is the keyword. Anything that should never be broken isn’t a convention. There’s no better convention than compiler error.
If you don't want an object mutated in Ruby, you can freeze it.
a = [1, 2]
def check_this(arr)
raise "doesn't start with 1" unless a.first == 1
end
check_this(a)
a << 3 # Raises "FrozenError (can't modify frozen Array)" because check_this froze `a`
Now, if you could temporarily freeze, and then unfreeze only the ones you froze, that could be really cool.Is that a missing feature in Ruby? You can't have a frozen reference to an object while retaining unfrozen ones in another scope? That's too bad.
Been bitten a few times by Array.sort().
Luckily there’s Array.toSorted() now.
https://www.typescriptlang.org/play/?#code/C4TwDgpgBAYg9nKBe...
1. You cannot return anything (say an immutable result that has consumed the input)
Okay, so don't return anything, just mutate the original. Except:
2. You cannot mutate the original, return nothing, but the mutated original isn't a subset of the original. For example: https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABB...