今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

Rust Ownership System Explained for JavaScript Developers

Timevolt 2026年06月05日 02:37 3 次阅读 来源:Dev.to

Rust Ownership System Explained for JavaScript Developers Quick context (why you're writing this) I was trying to rewrite a small utility I’d written in JavaScript—a function that takes a string, splits it into words, and returns the longest one. In JS it’s trivial: you pass the string around, mutate arrays, and nothing blows up. When I attempted the same thing in Rust, the compiler kept yelling at me about “use of moved value” and “cannot borrow as mutable because it is also borrowed as immutable”. I spent a good chunk of an afternoon staring at those errors, thinking I’d missed some syntax detail, only to realize the real issue was a completely different way of thinking about data. If you’ve ever felt that Rust’s compiler is being overly pedantic, you’re not alone—but once you grasp what it’s protecting you from, the frustration turns into appreciation. The Insight Rust doesn’t treat variables like JavaScript’s loosely‑typed references. Instead, it enforces ownership at compile time. Three ideas tend to surprise developers coming from a garbage‑collected world: Move semantics – assigning a value to another variable moves it; the original is no longer usable unless you explicitly clone it. Borrowing rules – you can have either many immutable references or exactly one mutable reference to a piece of data, but never both at the same time. Lifetimes – the compiler tracks how long references are valid, preventing dangling pointers without a garbage collector. The first two are the ones that trip people up most often, and they directly address the class of bugs JavaScript developers know all too well: accidental shared‑state mutations and use‑after‑free‑like mistakes (though in JS they show up as weird undefined values rather than crashes). Let’s look at each with a concrete example, show the common mistake, and then see how to do it right. How (with code) Move semantics – the “you can’t use it after you give it away” surprise fn main () { let greeting = String :: from

本文内容来源于互联网,版权归原作者所有
查看原文