Ownership adalah Konsep baru dalam bahasa pemrograman untuk mengalokasikan penggunaan memory . Kebanyakan bahasa pemrograman lainya menggunakan garbage collection untuk mengatur hal tersebut.
konsep penting untuk mempelajari rust https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#the-stack-and-the-heap
contoh ownership,
fn main() {
{
// println!("s value : {s}");
// s is not valid here, it’s not yet declared
let s = "hello"; // s is valid from this point forward
println!("s value : {s}");
// do stuff with s
}
// println!("s value : {s}"); // s tidak dapat diakses di luar scope
}
fn main() {
{
{
let mut s = String::from("hello");
// do stuff with s
s.push_str(", world!"); // push_str() appends a literal to a String
println!("{}", s); // This will print `hello, world!`
}
// println!("{}", s); // s tidak dapat diakses
}
// println!("s value : {s}"); // s tidak dapat diakses di luar scope
}
example:
let s1 = String::from("hello");
let s2 = s1;
When we assign s1
to s2
, the String
data is copied, meaning we copy the pointer, the length, and the capacity that are on the stack. We do not copy the data on the heap that the pointer refers to. In other words, the data representation in memory looks like Figure 4-2.
Figure 4-2: Representation in memory of the variable s2
that has a copy of the pointer, length, and capacity of s1