SlideShare a Scribd company logo
郭⾄至軒 [:kuoe0]
Mozilla
kuoe0.tw@gmail.com
Ownership
System in Rust
2016/07/12 @摩茲⼯工寮
4.8 Ownership[link]
Variable & Memory
A variable name is only a name.
It’s possible that a variable name can not access any
memory.
When a variable is declared, Rust allocates memory in
stack and heap (if need) for it.
When the owner of resources is destroyed, ALL
resources it owned would be released.
Variable & Memory
Stack
Heap
fn main() {
let v = vec![1, 2, 3];
}
dynamic memory
static memory
Variable & Memory
Stack
Heap
fn main() {
let v = vec![1, 2, 3];
}
dynamic memory
static memory
When the variable is destroyed…
fn main() {
let v = vec![1, 2, 3];
}
Variable & Memory
Stack
Heap
dynamic memory
static memory
All related resources will be destroyed, too!
Move By Default
Assignment operator is move semantics by default.
There is exactly one variable binding to any resource.
Avoid data racing to guarantee data consistency.
Move By Default
struct Point {
x: i32,
y: i32
}
fn main() {
let v1 = Point{ x: 10, y:
20};
let v2 = v1;
println!("{}", v1.x);
}
error: use of moved value: `v1.x` [--explain
E0382]
--> <anon>:9:20
8 |> let v2 = v1;
|> -- value moved here
9 |> println!("{}", v1.x);
|> ^^^^ value used here
after move
<std macros>:2:27: 2:58: note: in this
expansion of format_args!
<std macros>:3:1: 3:54: note: in this
expansion of print! (defined in <std macros>)
<anon>:9:5: 9:26: note: in this expansion of
println! (defined in <std macros>)
note: move occurs because `v1` has type
`Point`, which does not implement the `Copy`
trait
error: aborting due to previous error
compile
Move By Default
struct Point {
x: i32,
y: i32
}
fn main() {
let v1 = Point{ x: 10, y:
20};
let v2 = v1;
println!("{}", v1.x);
}
error: use of moved value: `v1.x` [--explain
E0382]
--> <anon>:9:20
8 |> let v2 = v1;
|> -- value moved here
9 |> println!("{}", v1.x);
|> ^^^^ value used here
after move
<std macros>:2:27: 2:58: note: in this
expansion of format_args!
<std macros>:3:1: 3:54: note: in this
expansion of print! (defined in <std macros>)
<anon>:9:5: 9:26: note: in this expansion of
println! (defined in <std macros>)
note: move occurs because `v1` has type
`Point`, which does not implement the `Copy`
trait
error: aborting due to previous error
compile
Use of moved value!
v1.x
Move By Default
stack
struct Point {
x: i32,
y: i32
}
fn main() {
let v1 = Point{ x: 10, y:
20};
let v2 = v1;
println!("{}", v1.x);
}
Point { x = 10, y = 20 }
names
v1
Move By Default
stack
struct Point {
x: i32,
y: i32
}
fn main() {
let v1 = Point{ x: 10, y:
20};
let v2 = v1;
println!("{}", v1.x);
}
Point { x = 10, y = 20 }
names
v1
v2
Copyable Type
The types which implement Copy trait can make
assignment operator be copy semantics.
Allow to use the variable which be copied.
All primitive types implement the Copy trait.
Copyable Type
fn main() {
let v1 = 10;
let v2 = v1;
println!("v1 = {}", v1);
println!("v2 = {}", v2);
}
v1 = 10
v2 = 10
Program ended.
run
Copyable Type
fn main() {
let v1 = 10;
let v2 = v1;
println!("v1 = {}", v1);
println!("v2 = {}", v2);
}
stacknames
v1 i32 { 10 }
Copyable Type
fn main() {
let v1 = 10;
let v2 = v1;
println!("v1 = {}", v1);
println!("v2 = {}", v2);
}
stacknames
v1 i32 { 10 }
v2 i32 { 10 }
Parameter Passing
Passing parameters is also move semantics by default
(no Copy trait).
Developers should return the ownership of parameters
by themselves.
Yes, you should return ten variables back if you pass
ten parameters into a function. 😜
Parameter Passing
struct Pt { x: i32, y: i32 }
fn dist(v: Pt) -> Pt {
println!("{}", v.x * v.x + v.y *
v.y);
v
}
fn main() {
let v = Pt{ x: 3, y: 4 };
let v = dist(v);
println!("{} {}", v.x, v.y);
}
struct Pt { x: i32, y: i32 }
fn dot(v1: Pt, v2: Pt) -> (Pt, Pt) {
println!("{}", v1.x * v2.x +
v1.y * v2.y);
(v1, v2)
}
fn main() {
let v1 = Pt{ x: 3, y: 4 };
let v2 = Pt{ x: 1, y: 2 };
let (v1, v2) = dot(v1, v2);
println!("{} {}", v1.x, v1.y);
println!("{} {}", v2.x, v2.y);
}
one parameter two parameters
Parameter Passing
struct Pt { x: i32 }
fn square(v: Pt) {
println!("{}", v.x * v.x);
}
fn main() {
let v = Pt{ x: 3 };
square(v);
println!("{}", v.x);
}
error: use of moved value: `v.x` [--explain
E0382]
--> <anon>:10:20
9 |> square(v);
|> - value moved here
10 |> println!("{}", v.x);
|> ^^^ value used here
after move
<std macros>:2:27: 2:58: note: in this
expansion of format_args!
<std macros>:3:1: 3:54: note: in this
expansion of print! (defined in <std macros>)
<anon>:10:5: 10:25: note: in this expansion
of println! (defined in <std macros>)
note: move occurs because `v` has type `Pt`,
which does not implement the `Copy` trait
error: aborting due to previous error
compile
Parameter Passing
struct Pt { x: i32 }
fn square(v: Pt) {
println!("{}", v.x * v.x);
}
fn main() {
let v = Pt{ x: 3 };
square(v);
println!("{}", v.x);
}
error: use of moved value: `v.x` [--explain
E0382]
--> <anon>:10:20
9 |> square(v);
|> - value moved here
10 |> println!("{}", v.x);
|> ^^^ value used here
after move
<std macros>:2:27: 2:58: note: in this
expansion of format_args!
<std macros>:3:1: 3:54: note: in this
expansion of print! (defined in <std macros>)
<anon>:10:5: 10:25: note: in this expansion
of println! (defined in <std macros>)
note: move occurs because `v` has type `Pt`,
which does not implement the `Copy` trait
error: aborting due to previous error
compile
v.x
Use of moved value!
4.9 Reference and Borrowing[link]
Syntax of Reference
fn main() {
let a = 1;
let b = &a; // &a is the reference to a
let mut c = 2;
let d = &mut c; // &mut c is the mutable
reference to c
}
Borrowing
Use the references to borrow the ownership.
The ownership will return to original owner when the
borrower is destroyed automatically.
References are immutable.
Allow multiple references to one variable.
A borrowed variable can be read but not written.
Only allow to borrow the variable with longer lifetime.
Borrowing
fn main() {
let orig = 0;
let b1 = &orig;
let b2 = &orig;
let b3 = &orig;
println!("b1 = {}", b1);
println!("b2 = {}", b2);
println!("b3 = {}", b3);
println!("orig = {}", orig);
}
b1 = 0
b2 = 0
b3 = 0
orig = 0
Program ended.
run
Borrowing
fn main() {
let mut x = 0;
{
let y = &x;
x += 1;
println!("{}", y);
}
println!("{}", x);
}
error: cannot assign to `x` because it is
borrowed [--explain E0506]
--> <anon>:5:9
4 |> let y = &x;
|> - borrow of `x` occurs
here
5 |> x += 1;
|> ^^^^^^ assignment to borrowed
`x` occurs here
error: aborting due to previous error
compile
Borrowing
fn main() {
let mut x = 0;
{
let y = &x;
x += 1;
println!("{}", y);
}
println!("{}", x);
}
error: cannot assign to `x` because it is
borrowed [--explain E0506]
--> <anon>:5:9
4 |> let y = &x;
|> - borrow of `x` occurs
here
5 |> x += 1;
|> ^^^^^^ assignment to borrowed
`x` occurs here
error: aborting due to previous error
compile
x += 1;
Cannot write the borrowed variable!
Borrowing
fn main() {
let y: &i32;
{
let x = 5;
y = &x;
}
println!("{}", y);
}
error: `x` does not live long enough
--> <anon>:5:14
5 |> y = &x;
|> ^
note: reference must be valid for the block
suffix following statement 0 at 2:16...
--> <anon>:2:17
2 |> let y: &i32;
|> ^
note: ...but borrowed value is only valid for
the block suffix following statement 0 at
4:18
--> <anon>:4:19
4 |> let x = 5;
|> ^
error: aborting due to previous error
compile
Borrowing
fn main() {
let y: &i32;
{
let x = 5;
y = &x;
}
println!("{}", y);
}
error: `x` does not live long enough
--> <anon>:5:14
5 |> y = &x;
|> ^
note: reference must be valid for the block
suffix following statement 0 at 2:16...
--> <anon>:2:17
2 |> let y: &i32;
|> ^
note: ...but borrowed value is only valid for
the block suffix following statement 0 at
4:18
--> <anon>:4:19
4 |> let x = 5;
|> ^
error: aborting due to previous error
compile
y = &x;
Lifetime of x is shorter than y.
Borrowing
fn main() {
let y: &i32;
let x = 5;
y = &x;
println!("{}", y);
}
error: `x` does not live long enough
--> <anon>:4:10
4 |> y = &x;
|> ^
note: reference must be valid for the block
suffix following statement 0 at 2:16...
--> <anon>:2:17
2 |> let y: &i32;
|> ^
note: ...but borrowed value is only valid for
the block suffix following statement 1 at
3:14
--> <anon>:3:15
3 |> let x = 5;
|> ^
error: aborting due to previous error
compile
Borrowing
fn main() {
let y: &i32;
let x = 5;
y = &x;
println!("{}", y);
}
error: `x` does not live long enough
--> <anon>:4:10
4 |> y = &x;
|> ^
note: reference must be valid for the block
suffix following statement 0 at 2:16...
--> <anon>:2:17
2 |> let y: &i32;
|> ^
note: ...but borrowed value is only valid for
the block suffix following statement 1 at
3:14
--> <anon>:3:15
3 |> let x = 5;
|> ^
error: aborting due to previous error
compile
y = &x;
Lifetime of x is shorter than y.
Borrowing
struct Pt { x: i32, y: i32 }
fn dot(v1: Pt, v2: Pt) -> (Pt, Pt) {
println!("{}", v1.x * v2.x +
v1.y * v2.y);
(v1, v2)
}
fn main() {
let v1 = Pt{ x: 3, y: 4 };
let v2 = Pt{ x: 1, y: 2 };
let (v1, v2) = dot(v1, v2);
println!("{} {}", v1.x, v1.y);
println!("{} {}", v2.x, v2.y);
}
struct Pt { x: i32, y: i32 }
fn dot(v1: &Pt, v2: &Pt) {
println!("{}", v1.x * v2.x +
v1.y * v2.y);
}
fn main() {
let v1 = Pt{ x: 3, y: 4 };
let v2 = Pt{ x: 1, y: 2 };
dot(&v1, &v2);
println!("{} {}", v1.x, v1.y);
println!("{} {}", v2.x, v2.y);
}
Borrowing
struct Pt { x: i32, y: i32 }
fn dot(v1: Pt, v2: Pt) -> (Pt, Pt) {
println!("{}", v1.x * v2.x +
v1.y * v2.y);
(v1, v2)
}
fn main() {
let v1 = Pt{ x: 3, y: 4 };
let v2 = Pt{ x: 1, y: 2 };
let (v1, v2) = dot(v1, v2);
println!("{} {}", v1.x, v1.y);
println!("{} {}", v2.x, v2.y);
}
struct Pt { x: i32, y: i32 }
fn dot(v1: &Pt, v2: &Pt) {
println!("{}", v1.x * v2.x +
v1.y * v2.y);
}
fn main() {
let v1 = Pt{ x: 3, y: 4 };
let v2 = Pt{ x: 1, y: 2 };
dot(&v1, &v2);
println!("{} {}", v1.x, v1.y);
println!("{} {}", v2.x, v2.y);
}
Mutable Borrowing
Use mutable references only if you need to change the values
you borrowed.
Only allow to borrow a mutable variables as a mutable
reference.
There is exactly one mutable reference to a variable.
A variable borrowed as a mutable reference can not be
borrowed as immutable references.
A variable borrowed as a mutable reference can not be used
until the end of borrowing.
Mutable Borrowing
fn main() {
let mut x = 0;
{
let y = &mut x;
*y += 1;
}
println!("x = {}", x);
}
x = 1
Program ended.
run
Mutable Borrowing
fn main() {
let mut x = 0;
{
let y = &mut x;
let z = &mut x;
*y += 1;
}
println!("x = {}", x);
}
error: cannot borrow `x` as mutable more than
once at a time [--explain E0499]
--> <anon>:5:22
4 |> let y = &mut x;
|> - first mutable
borrow occurs here
5 |> let z = &mut x;
|> ^ second mutable
borrow occurs here
6 |> *y += 1;
7 |> }
|> - first borrow ends here
error: aborting due to previous error
compile
Mutable Borrowing
fn main() {
let mut x = 0;
{
let y = &mut x;
let z = &mut x;
*y += 1;
}
println!("x = {}", x);
}
error: cannot borrow `x` as mutable more than
once at a time [--explain E0499]
--> <anon>:5:22
4 |> let y = &mut x;
|> - first mutable
borrow occurs here
5 |> let z = &mut x;
|> ^ second mutable
borrow occurs here
6 |> *y += 1;
7 |> }
|> - first borrow ends here
error: aborting due to previous error
compile
let z = &mut x;
Cannot borrow x as mutable reference more than once!
Mutable Borrowing
fn main() {
let mut x = 0;
{
let y = &mut x;
let z = &x;
*y += 1;
}
println!("x = {}", x);
}
error: cannot borrow `x` as immutable because
it is also borrowed as mutable [--explain
E0502]
--> <anon>:6:18
4 |> let y = &mut x;
|> - mutable borrow
occurs here
5 |> *y += 1;
6 |> let z = &x;
|> ^ immutable borrow
occurs here
7 |> }
|> - mutable borrow ends here
error: aborting due to previous error
compile
Mutable Borrowing
fn main() {
let mut x = 0;
{
let y = &mut x;
let z = &x;
*y += 1;
}
println!("x = {}", x);
}
error: cannot borrow `x` as immutable because
it is also borrowed as mutable [--explain
E0502]
--> <anon>:6:18
4 |> let y = &mut x;
|> - mutable borrow
occurs here
5 |> *y += 1;
6 |> let z = &x;
|> ^ immutable borrow
occurs here
7 |> }
|> - mutable borrow ends here
error: aborting due to previous error
compile
let z = &x;
Cannot borrow the variable been borrowed as a mutable reference!
Mutable Borrowing
fn main() {
let mut x = 0;
{
let y = &mut x;
let z = x + 1;
}
println!("x = {}", x);
}
error: cannot use `x` because it was mutably
borrowed [E0503]
--> <anon>:5:17
5 |> let z = x + 1;
|> ^
note: borrow of `x` occurs here
--> <anon>:4:22
4 |> let y = &mut x;
|> ^
error: aborting due to previous error
compile
Mutable Borrowing
fn main() {
let mut x = 0;
{
let y = &mut x;
let z = x + 1;
}
println!("x = {}", x);
}
error: cannot use `x` because it was mutably
borrowed [E0503]
--> <anon>:5:17
5 |> let z = x + 1;
|> ^
note: borrow of `x` occurs here
--> <anon>:4:22
4 |> let y = &mut x;
|> ^
error: aborting due to previous error
compile
let z = x + 1;
Cannot access the variable been borrowed as a mutable reference.
Thinking in Scopes
fn main() {
let mut x = 0;
let y = &mut x;
*y += 1;
println!("x = {}", x);
}
Why compile error?
Thinking in Scopes(cont’)
fn main() {
let mut x = 0;
let y = &mut x;
*y += 1;
println!("x = {}", x);
}
error: cannot borrow `x` as immutable because
it is also borrowed as mutable [--explain
E0502]
--> <anon>:5:24
3 |> let y = &mut x;
|> - mutable borrow occurs
here
4 |> *y += 1;
5 |> println!("x = {}", x);
|> ^ immutable
borrow occurs here
6 |> }
|> - mutable borrow ends here
<std macros>:2:27: 2:58: note: in this
expansion of format_args!
<std macros>:3:1: 3:54: note: in this
expansion of print! (defined in <std macros>)
<anon>:5:5: 5:27: note: in this expansion of
println! (defined in <std macros>)
error: aborting due to previous error
compile
Thinking in Scopes(cont’)
fn main() {
let mut x = 0;
let y = &mut x;
*y += 1;
println!("x = {}", x);
}
error: cannot borrow `x` as immutable because
it is also borrowed as mutable [--explain
E0502]
--> <anon>:5:24
3 |> let y = &mut x;
|> - mutable borrow occurs
here
4 |> *y += 1;
5 |> println!("x = {}", x);
|> ^ immutable
borrow occurs here
6 |> }
|> - mutable borrow ends here
<std macros>:2:27: 2:58: note: in this
expansion of format_args!
<std macros>:3:1: 3:54: note: in this
expansion of print! (defined in <std macros>)
<anon>:5:5: 5:27: note: in this expansion of
println! (defined in <std macros>)
error: aborting due to previous error
compile
println!("x = {}", x);
Immutable borrow occurs here!
Iterator Invalidation
fn main() {
let mut v = vec![1, 2, 3];
for i in &v {
println!("{}", i);
v.push(34);
}
}
error: cannot borrow `v` as mutable because
it is also borrowed as immutable [--explain
E0502]
--> <anon>:6:9
4 |> for i in &v {
|> - immutable borrow occurs
here
5 |> println!("{}", i);
6 |> v.push(34);
|> ^ mutable borrow occurs here
7 |> }
|> - immutable borrow ends here
error: aborting due to previous error
compile
Iterator Invalidation
fn main() {
let mut v = vec![1, 2, 3];
for i in &v {
println!("{}", i);
v.push(34);
}
}
error: cannot borrow `v` as mutable because
it is also borrowed as immutable [--explain
E0502]
--> <anon>:6:9
4 |> for i in &v {
|> - immutable borrow occurs
here
5 |> println!("{}", i);
6 |> v.push(34);
|> ^ mutable borrow occurs here
7 |> }
|> - immutable borrow ends here
error: aborting due to previous error
compile
v.push(34);
push(&mut self, …) try to borrow v as a mutable reference!
4.10 Lifetimes[link]
Syntax of Lifetimes Specifier
fn fn2<'a>(x: &'a i32) -> &'a i32 {
// do something
}
Syntax of Lifetimes Specifier
fn fn2<'a>(x: &'a i32) -> &'a i32 {
// do something
}
'a 'a 'a
input lifetime output lifetime
Syntax of Lifetimes Specifier
// lifetime with mutable reference
fn foo<'a>(x: &'a mut i32) -> &'a mut i32 {
// do something
}
// lifetime in struct
struct Foo<'a> {
x: &'a i32
}
// lifetime with impl
impl<'a> Foo<'a> {
fn x(&self) -> &'a i32 { self.x }
}
Lifetimes Specifier
All references need lifetimes.
Explicit lifetimes are used to make lifetime inference
unambiguous.
Must give explicit lifetimes for struct contain reference
members.
No need to give explicit lifetimes to the functions
without references return.
Lifetimes Specifier
struct Foo<'a> {
x: &'a i32
}
impl<'a> Foo<'a> {
fn x(&self) -> &'a i32 { self.x }
}
fn main() {
let y = 5;
let f = Foo { x: &y };
println!("{}", f.x);
println!("{}", f.x());
}
5
5
Program ended.
run
Lifetime Inference
Each elided lifetime of arguments becomes a distinct
lifetime parameter.
If there is exactly one input lifetime, all elided lifetimes
of the return values will be as same as the input
lifetime.
If there is &self in input lifetimes, all elided lifetimes of
the return values will be as same as &self.
Lifetime Inference (valid)
fn print(s: &str); // elided
fn print<'a>(s: &'a str); // expanded
//////////
fn substr(s: &str, until: u32) -> &str; // elided
fn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded
//////////
fn get_mut(&mut self) -> &mut T; // elided
fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded
Lifetime Inference (invalid)
fn get_str() -> &str; // ILLEGAL, no inputs
//////////
fn frob(s: &str, t: &str) -> &str; // Two input
lifetimes
fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Output
lifetime is ambiguous
Static Lifetime
Some resources have the lifetime of the entire
program.
No need to give explicit lifetime for functions return
static resources.
Lifetimes Specifier
static FIVE: i32 = 5;
fn get_five() -> &'static i32 {
&FIVE
}
fn main() {
let x = get_five();
println!("x = {}", x);
}
x = 5
Program ended.
run
Thanks!
CC-BY-SA

More Related Content

What's hot

ElastiCacheを利用する上でキャッシュをどのように有効に使うべきか
ElastiCacheを利用する上でキャッシュをどのように有効に使うべきかElastiCacheを利用する上でキャッシュをどのように有効に使うべきか
ElastiCacheを利用する上でキャッシュをどのように有効に使うべきか
Amazon Web Services Japan
 
(책 소개) 실전 카프카 개발부터 운영까지
(책 소개) 실전 카프카 개발부터 운영까지(책 소개) 실전 카프카 개발부터 운영까지
(책 소개) 실전 카프카 개발부터 운영까지
Jay Park
 
Harbor RegistryのReplication機能
Harbor RegistryのReplication機能Harbor RegistryのReplication機能
Harbor RegistryのReplication機能
Masanori Nara
 
C# 8.0 null許容参照型
C# 8.0 null許容参照型C# 8.0 null許容参照型
C# 8.0 null許容参照型
信之 岩永
 
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
Yoshifumi Kawai
 
こんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツールこんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツール
dcubeio
 
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
Amazon Web Services Korea
 
테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템
QooJuice
 
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 SeoulElastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
SeungYong Oh
 
How I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowHow I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with Airflow
PyData
 
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
Amazon Web Services Korea
 
Swaggerでのapi開発よもやま話
Swaggerでのapi開発よもやま話Swaggerでのapi開発よもやま話
Swaggerでのapi開発よもやま話
KEISUKE KONISHI
 
AWS Black Belt Techシリーズ AWS Management Console
AWS Black Belt Techシリーズ AWS Management ConsoleAWS Black Belt Techシリーズ AWS Management Console
AWS Black Belt Techシリーズ AWS Management Console
Amazon Web Services Japan
 
개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 intro개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 intro
Seongyun Byeon
 
NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현
noerror
 
Windows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCPWindows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCP
Seungmo Koo
 
DB Monitoring 개념 및 활용 (박명규)
DB Monitoring 개념 및 활용 (박명규)DB Monitoring 개념 및 활용 (박명규)
DB Monitoring 개념 및 활용 (박명규)
WhaTap Labs
 
Secrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on KubernetesSecrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on Kubernetes
Bruno Borges
 
Open Match Deep Dive
Open Match Deep DiveOpen Match Deep Dive
Open Match Deep Dive
Samir Hammoudi
 
웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우
IMQA
 

What's hot (20)

ElastiCacheを利用する上でキャッシュをどのように有効に使うべきか
ElastiCacheを利用する上でキャッシュをどのように有効に使うべきかElastiCacheを利用する上でキャッシュをどのように有効に使うべきか
ElastiCacheを利用する上でキャッシュをどのように有効に使うべきか
 
(책 소개) 실전 카프카 개발부터 운영까지
(책 소개) 실전 카프카 개발부터 운영까지(책 소개) 실전 카프카 개발부터 운영까지
(책 소개) 실전 카프카 개발부터 운영까지
 
Harbor RegistryのReplication機能
Harbor RegistryのReplication機能Harbor RegistryのReplication機能
Harbor RegistryのReplication機能
 
C# 8.0 null許容参照型
C# 8.0 null許容参照型C# 8.0 null許容参照型
C# 8.0 null許容参照型
 
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
「黒騎士と白の魔王」gRPCによるHTTP/2 - API, Streamingの実践
 
こんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツールこんなに使える!今どきのAPIドキュメンテーションツール
こんなに使える!今どきのAPIドキュメンテーションツール
 
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
쿠키런: 킹덤 대규모 인프라 및 서버 운영 사례 공유 [데브시스터즈 - 레벨 200] - 발표자: 용찬호, R&D 엔지니어, 데브시스터즈 ...
 
테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템테라로 살펴본 MMORPG의 논타겟팅 시스템
테라로 살펴본 MMORPG의 논타겟팅 시스템
 
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 SeoulElastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
Elastic Stack 을 이용한 게임 서비스 통합 로깅 플랫폼 - elastic{on} 2019 Seoul
 
How I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowHow I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with Airflow
 
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
 
Swaggerでのapi開発よもやま話
Swaggerでのapi開発よもやま話Swaggerでのapi開発よもやま話
Swaggerでのapi開発よもやま話
 
AWS Black Belt Techシリーズ AWS Management Console
AWS Black Belt Techシリーズ AWS Management ConsoleAWS Black Belt Techシリーズ AWS Management Console
AWS Black Belt Techシリーズ AWS Management Console
 
개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 intro개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 intro
 
NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현
 
Windows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCPWindows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCP
 
DB Monitoring 개념 및 활용 (박명규)
DB Monitoring 개념 및 활용 (박명규)DB Monitoring 개념 및 활용 (박명규)
DB Monitoring 개념 및 활용 (박명규)
 
Secrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on KubernetesSecrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on Kubernetes
 
Open Match Deep Dive
Open Match Deep DiveOpen Match Deep Dive
Open Match Deep Dive
 
웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우
 

Viewers also liked

面試面試面試,因為很重要所以要說三次!
面試面試面試,因為很重要所以要說三次!面試面試面試,因為很重要所以要說三次!
面試面試面試,因為很重要所以要說三次!
Chih-Hsuan Kuo
 
[ACM-ICPC] Tree Isomorphism
[ACM-ICPC] Tree Isomorphism[ACM-ICPC] Tree Isomorphism
[ACM-ICPC] Tree Isomorphism
Chih-Hsuan Kuo
 
[ACM-ICPC] Bipartite Matching
[ACM-ICPC] Bipartite Matching[ACM-ICPC] Bipartite Matching
[ACM-ICPC] Bipartite Matching
Chih-Hsuan Kuo
 
[ACM-ICPC] Dinic's Algorithm
[ACM-ICPC] Dinic's Algorithm[ACM-ICPC] Dinic's Algorithm
[ACM-ICPC] Dinic's Algorithm
Chih-Hsuan Kuo
 
面試心得
面試心得面試心得
面試心得
澐 向
 
面試經驗分享
面試經驗分享面試經驗分享
面試經驗分享
俊儀 郭
 
簡易的面試心得分享
簡易的面試心得分享簡易的面試心得分享
簡易的面試心得分享
Jack Wang
 
Asp.net mvc 概觀介紹
Asp.net mvc 概觀介紹Asp.net mvc 概觀介紹
Asp.net mvc 概觀介紹
Alan Tsai
 
張忠謀自傳
張忠謀自傳張忠謀自傳
張忠謀自傳
5045033
 
關於測試,我說的其實是......
關於測試,我說的其實是......關於測試,我說的其實是......
關於測試,我說的其實是......
hugo lu
 
吳明展的履歷 My Resume 2009 (ppt)
吳明展的履歷 My Resume 2009 (ppt)吳明展的履歷 My Resume 2009 (ppt)
吳明展的履歷 My Resume 2009 (ppt)
Anderson Wu, PMP, CSM, 吳明展
 

Viewers also liked (11)

面試面試面試,因為很重要所以要說三次!
面試面試面試,因為很重要所以要說三次!面試面試面試,因為很重要所以要說三次!
面試面試面試,因為很重要所以要說三次!
 
[ACM-ICPC] Tree Isomorphism
[ACM-ICPC] Tree Isomorphism[ACM-ICPC] Tree Isomorphism
[ACM-ICPC] Tree Isomorphism
 
[ACM-ICPC] Bipartite Matching
[ACM-ICPC] Bipartite Matching[ACM-ICPC] Bipartite Matching
[ACM-ICPC] Bipartite Matching
 
[ACM-ICPC] Dinic's Algorithm
[ACM-ICPC] Dinic's Algorithm[ACM-ICPC] Dinic's Algorithm
[ACM-ICPC] Dinic's Algorithm
 
面試心得
面試心得面試心得
面試心得
 
面試經驗分享
面試經驗��享面試經驗分享
面試經驗分享
 
簡易的面試心得分享
簡易的面試心得分享簡易的面試心得分享
簡易的面試心得分享
 
Asp.net mvc 概觀介紹
Asp.net mvc 概觀介紹Asp.net mvc 概觀介紹
Asp.net mvc 概觀介紹
 
張忠謀自傳
張忠謀自傳張忠謀自傳
張忠謀自傳
 
關於測試,我說的其實是......
關於測試,我說的其實是......關於測試,我說的其實是......
關於測試,我說的其實是......
 
吳明展的履歷 My Resume 2009 (ppt)
吳明展的履歷 My Resume 2009 (ppt)吳明展的履歷 My Resume 2009 (ppt)
吳明展的履歷 My Resume 2009 (ppt)
 

Similar to Ownership System in Rust

Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
sangam biradar
 
Rust
RustRust
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
pramode_ce
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
nikomatsakis
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
Paweł Rusin
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
Yandex
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
Eelco Visser
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
kinan keshkeh
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может ��ыть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Yandex
 
The Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S GuideThe Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S Guide
Stephen Chin
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
Geeks Anonymes
 
Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup
Claudio Capobianco
 
[CONFidence 2016] Mateusz Kocielski - Torturing the PHP interpreter
[CONFidence 2016] Mateusz Kocielski - Torturing the PHP interpreter [CONFidence 2016] Mateusz Kocielski - Torturing the PHP interpreter
[CONFidence 2016] Mateusz Kocielski - Torturing the PHP interpreter
PROIDEA
 
Torturing the PHP interpreter
Torturing the PHP interpreterTorturing the PHP interpreter
Torturing the PHP interpreter
Logicaltrust pl
 
What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)
David Evans
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
Saifur Rahman
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
Leonardo Borges
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
oscon2007
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
Claudio Capobianco
 

Similar to Ownership System in Rust (20)

Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
 
Rust
RustRust
Rust
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
 
The Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S GuideThe Java Fx Platform – A Java Developer’S Guide
The Java Fx Platform – A Java Developer’S Guide
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup Rust Intro @ Roma Rust meetup
Rust Intro @ Roma Rust meetup
 
[CONFidence 2016] Mateusz Kocielski - Torturing the PHP interpreter
[CONFidence 2016] Mateusz Kocielski - Torturing the PHP interpreter [CONFidence 2016] Mateusz Kocielski - Torturing the PHP interpreter
[CONFidence 2016] Mateusz Kocielski - Torturing the PHP interpreter
 
Torturing the PHP interpreter
Torturing the PHP interpreterTorturing the PHP interpreter
Torturing the PHP interpreter
 
What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)What the &~#@&lt;!? (Pointers in Rust)
What the &~#@&lt;!? (Pointers in Rust)
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 

More from Chih-Hsuan Kuo

[Mozilla] content-select
[Mozilla] content-select[Mozilla] content-select
[Mozilla] content-select
Chih-Hsuan Kuo
 
在開始工作以前,我以為我會寫扣。
在開始工作以前,我以為我會寫扣。在開始工作以前,我以為我會寫扣。
在開始工作以前,我以為我會寫扣。
Chih-Hsuan Kuo
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
Chih-Hsuan Kuo
 
Use C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoUse C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in Gecko
Chih-Hsuan Kuo
 
Pocket Authentication with OAuth on Firefox OS
Pocket Authentication with OAuth on Firefox OSPocket Authentication with OAuth on Firefox OS
Pocket Authentication with OAuth on Firefox OS
Chih-Hsuan Kuo
 
Necko walkthrough
Necko walkthroughNecko walkthrough
Necko walkthrough
Chih-Hsuan Kuo
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
Chih-Hsuan Kuo
 
面試心得分享
面試心得分享面試心得分享
面試心得分享
Chih-Hsuan Kuo
 
Windows 真的不好用...
Windows 真的不好用...Windows 真的不好用...
Windows 真的不好用...
Chih-Hsuan Kuo
 
Python @Wheel Lab
Python @Wheel LabPython @Wheel Lab
Python @Wheel Lab
Chih-Hsuan Kuo
 
Introduction to VP8
Introduction to VP8Introduction to VP8
Introduction to VP8
Chih-Hsuan Kuo
 
Python @NCKU CSIE
Python @NCKU CSIEPython @NCKU CSIE
Python @NCKU CSIE
Chih-Hsuan Kuo
 
[ACM-ICPC] Disjoint Set
[ACM-ICPC] Disjoint Set[ACM-ICPC] Disjoint Set
[ACM-ICPC] Disjoint Set
Chih-Hsuan Kuo
 
[ACM-ICPC] Traversal
[ACM-ICPC] Traversal[ACM-ICPC] Traversal
[ACM-ICPC] Traversal
Chih-Hsuan Kuo
 
[ACM-ICPC] UVa-10245
[ACM-ICPC] UVa-10245[ACM-ICPC] UVa-10245
[ACM-ICPC] UVa-10245
Chih-Hsuan Kuo
 
[ACM-ICPC] Sort
[ACM-ICPC] Sort[ACM-ICPC] Sort
[ACM-ICPC] Sort
Chih-Hsuan Kuo
 
[ACM-ICPC] Efficient Algorithm
[ACM-ICPC] Efficient Algorithm[ACM-ICPC] Efficient Algorithm
[ACM-ICPC] Efficient Algorithm
Chih-Hsuan Kuo
 
[ACM-ICPC] Top-down & Bottom-up
[ACM-ICPC] Top-down & Bottom-up[ACM-ICPC] Top-down & Bottom-up
[ACM-ICPC] Top-down & Bottom-up
Chih-Hsuan Kuo
 
[ACM-ICPC] About I/O
[ACM-ICPC] About I/O[ACM-ICPC] About I/O
[ACM-ICPC] About I/O
Chih-Hsuan Kuo
 

More from Chih-Hsuan Kuo (20)

[Mozilla] content-select
[Mozilla] content-select[Mozilla] content-select
[Mozilla] content-select
 
在開始工作以前,我以為我會寫扣。
在開始工作以前,我以為我會寫扣。在開始工作以前,我以為我會寫扣。
在開始工作以前,我以為我會寫扣。
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
 
Use C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoUse C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in Gecko
 
Pocket Authentication with OAuth on Firefox OS
Pocket Authentication with OAuth on Firefox OSPocket Authentication with OAuth on Firefox OS
Pocket Authentication with OAuth on Firefox OS
 
Necko walkthrough
Necko walkthroughNecko walkthrough
Necko walkthrough
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 
應徵軟體工程師
應徵軟體工程師應徵軟體工程師
應徵軟體工程師
 
面試心得分享
面試心得分享面試心得分享
面試心得分享
 
Windows 真的不好用...
Windows 真的不好用...Windows 真的不好用...
Windows 真的不好用...
 
Python @Wheel Lab
Python @Wheel LabPython @Wheel Lab
Python @Wheel Lab
 
Introduction to VP8
Introduction to VP8Introduction to VP8
Introduction to VP8
 
Python @NCKU CSIE
Python @NCKU CSIEPython @NCKU CSIE
Python @NCKU CSIE
 
[ACM-ICPC] Disjoint Set
[ACM-ICPC] Disjoint Set[ACM-ICPC] Disjoint Set
[ACM-ICPC] Disjoint Set
 
[ACM-ICPC] Traversal
[ACM-ICPC] Traversal[ACM-ICPC] Traversal
[ACM-ICPC] Traversal
 
[ACM-ICPC] UVa-10245
[ACM-ICPC] UVa-10245[ACM-ICPC] UVa-10245
[ACM-ICPC] UVa-10245
 
[ACM-ICPC] Sort
[ACM-ICPC] Sort[ACM-ICPC] Sort
[ACM-ICPC] Sort
 
[ACM-ICPC] Efficient Algorithm
[ACM-ICPC] Efficient Algorithm[ACM-ICPC] Efficient Algorithm
[ACM-ICPC] Efficient Algorithm
 
[ACM-ICPC] Top-down & Bottom-up
[ACM-ICPC] Top-down & Bottom-up[ACM-ICPC] Top-down & Bottom-up
[ACM-ICPC] Top-down & Bottom-up
 
[ACM-ICPC] About I/O
[ACM-ICPC] About I/O[ACM-ICPC] About I/O
[ACM-ICPC] About I/O
 

Recently uploaded

240717 ProPILE - Probing Privacy Leakage in Large Language Models.pdf
240717 ProPILE - Probing Privacy Leakage in Large Language Models.pdf240717 ProPILE - Probing Privacy Leakage in Large Language Models.pdf
240717 ProPILE - Probing Privacy Leakage in Large Language Models.pdf
CS Kwak
 
vSAN_Tutorial_Presentation with important topics
vSAN_Tutorial_Presentation with important  topicsvSAN_Tutorial_Presentation with important  topics
vSAN_Tutorial_Presentation with important topics
abhilashspt
 
Empowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - GrawlixEmpowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - Grawlix
Aarisha Shaikh
 
Amazon Music Spelling Correction - SIGIR 2024
Amazon Music Spelling Correction - SIGIR 2024Amazon Music Spelling Correction - SIGIR 2024
Amazon Music Spelling Correction - SIGIR 2024
siddharth1729
 
Security for database administrator to enhance security
Security for database administrator to enhance securitySecurity for database administrator to enhance security
Security for database administrator to enhance security
ssuser20fcbe
 
UW Cert degree offer diploma
UW Cert degree offer diploma UW Cert degree offer diploma
UW Cert degree offer diploma
dakyuhe
 
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
andrehoraa
 
Generative AI The Key to Smarter, Faster IT Development.pdf
Generative AI The Key to Smarter, Faster IT Development.pdfGenerative AI The Key to Smarter, Faster IT Development.pdf
Generative AI The Key to Smarter, Faster IT Development.pdf
ayushiqss
 
PathSpotter: Exploring Tested Paths to Discover Missing Tests (FSE 2024)
PathSpotter: Exploring Tested Paths to Discover Missing Tests (FSE 2024)PathSpotter: Exploring Tested Paths to Discover Missing Tests (FSE 2024)
PathSpotter: Exploring Tested Paths to Discover Missing Tests (FSE 2024)
andrehoraa
 
CrushFTP 10.4.0.29 PC Software - WhizNews
CrushFTP 10.4.0.29 PC Software - WhizNewsCrushFTP 10.4.0.29 PC Software - WhizNews
CrushFTP 10.4.0.29 PC Software - WhizNews
Eman Nisar
 
SAP implementation steps PDF - Zyple Software
SAP implementation steps PDF - Zyple SoftwareSAP implementation steps PDF - Zyple Software
SAP implementation steps PDF - Zyple Software
Zyple Software
 
pgroll - Zero-downtime, reversible, schema migrations for Postgres
pgroll - Zero-downtime, reversible, schema migrations for Postgrespgroll - Zero-downtime, reversible, schema migrations for Postgres
pgroll - Zero-downtime, reversible, schema migrations for Postgres
Tudor Golubenco
 
Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)
andrehoraa
 
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
Shane Coughlan
 
05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching
quanhoangd129
 
iBirds Services - Comprehensive Salesforce CRM and Software Development Solut...
iBirds Services - Comprehensive Salesforce CRM and Software Development Solut...iBirds Services - Comprehensive Salesforce CRM and Software Development Solut...
iBirds Services - Comprehensive Salesforce CRM and Software Development Solut...
vijayatibirds
 
Why Laravel is the Best PHP Framework An Introduction.pdf
Why Laravel is the Best PHP Framework An Introduction.pdfWhy Laravel is the Best PHP Framework An Introduction.pdf
Why Laravel is the Best PHP Framework An Introduction.pdf
Grey Space Computing
 
Unlocking the Future of Artificial Intelligence
Unlocking the Future of Artificial IntelligenceUnlocking the Future of Artificial Intelligence
Unlocking the Future of Artificial Intelligence
dorinIonescu
 
08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching
quanhoangd129
 
Crowd Strike\Windows Update Issue: Overview and Current Status
Crowd Strike\Windows Update Issue: Overview and Current StatusCrowd Strike\Windows Update Issue: Overview and Current Status
Crowd Strike\Windows Update Issue: Overview and Current Status
ramaganesan0504
 

Recently uploaded (20)

240717 ProPILE - Probing Privacy Leakage in Large Language Models.pdf
240717 ProPILE - Probing Privacy Leakage in Large Language Models.pdf240717 ProPILE - Probing Privacy Leakage in Large Language Models.pdf
240717 ProPILE - Probing Privacy Leakage in Large Language Models.pdf
 
vSAN_Tutorial_Presentation with important topics
vSAN_Tutorial_Presentation with important  topicsvSAN_Tutorial_Presentation with important  topics
vSAN_Tutorial_Presentation with important topics
 
Empowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - GrawlixEmpowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - Grawlix
 
Amazon Music Spelling Correction - SIGIR 2024
Amazon Music Spelling Correction - SIGIR 2024Amazon Music Spelling Correction - SIGIR 2024
Amazon Music Spelling Correction - SIGIR 2024
 
Security for database administrator to enhance security
Security for database administrator to enhance securitySecurity for database administrator to enhance security
Security for database administrator to enhance security
 
UW Cert degree offer diploma
UW Cert degree offer diploma UW Cert degree offer diploma
UW Cert degree offer diploma
 
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
 
Generative AI The Key to Smarter, Faster IT Development.pdf
Generative AI The Key to Smarter, Faster IT Development.pdfGenerative AI The Key to Smarter, Faster IT Development.pdf
Generative AI The Key to Smarter, Faster IT Development.pdf
 
PathSpotter: Exploring Tested Paths to Discover Missing Tests (FSE 2024)
PathSpotter: Exploring Tested Paths to Discover Missing Tests (FSE 2024)PathSpotter: Exploring Tested Paths to Discover Missing Tests (FSE 2024)
PathSpotter: Exploring Tested Paths to Discover Missing Tests (FSE 2024)
 
CrushFTP 10.4.0.29 PC Software - WhizNews
CrushFTP 10.4.0.29 PC Software - WhizNewsCrushFTP 10.4.0.29 PC Software - WhizNews
CrushFTP 10.4.0.29 PC Software - WhizNews
 
SAP implementation steps PDF - Zyple Software
SAP implementation steps PDF - Zyple SoftwareSAP implementation steps PDF - Zyple Software
SAP implementation steps PDF - Zyple Software
 
pgroll - Zero-downtime, reversible, schema migrations for Postgres
pgroll - Zero-downtime, reversible, schema migrations for Postgrespgroll - Zero-downtime, reversible, schema migrations for Postgres
pgroll - Zero-downtime, reversible, schema migrations for Postgres
 
Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)
 
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
OpenChain Webinar: IAV, TimeToAct and ISO/IEC 5230 - Third-Party Certificatio...
 
05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching
 
iBirds Services - Comprehensive Salesforce CRM and Software Development Solut...
iBirds Services - Comprehensive Salesforce CRM and Software Development Solut...iBirds Services - Comprehensive Salesforce CRM and Software Development Solut...
iBirds Services - Comprehensive Salesforce CRM and Software Development Solut...
 
Why Laravel is the Best PHP Framework An Introduction.pdf
Why Laravel is the Best PHP Framework An Introduction.pdfWhy Laravel is the Best PHP Framework An Introduction.pdf
Why Laravel is the Best PHP Framework An Introduction.pdf
 
Unlocking the Future of Artificial Intelligence
Unlocking the Future of Artificial IntelligenceUnlocking the Future of Artificial Intelligence
Unlocking the Future of Artificial Intelligence
 
08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching
 
Crowd Strike\Windows Update Issue: Overview and Current Status
Crowd Strike\Windows Update Issue: Overview and Current StatusCrowd Strike\Windows Update Issue: Overview and Current Status
Crowd Strike\Windows Update Issue: Overview and Current Status
 

Ownership System in Rust

  • 3. Variable & Memory A variable name is only a name. It’s possible that a variable name can not access any memory. When a variable is declared, Rust allocates memory in stack and heap (if need) for it. When the owner of resources is destroyed, ALL resources it owned would be released.
  • 4. Variable & Memory Stack Heap fn main() { let v = vec![1, 2, 3]; } dynamic memory static memory
  • 5. Variable & Memory Stack Heap fn main() { let v = vec![1, 2, 3]; } dynamic memory static memory When the variable is destroyed…
  • 6. fn main() { let v = vec![1, 2, 3]; } Variable & Memory Stack Heap dynamic memory static memory All related resources will be destroyed, too!
  • 7. Move By Default Assignment operator is move semantics by default. There is exactly one variable binding to any resource. Avoid data racing to guarantee data consistency.
  • 8. Move By Default struct Point { x: i32, y: i32 } fn main() { let v1 = Point{ x: 10, y: 20}; let v2 = v1; println!("{}", v1.x); } error: use of moved value: `v1.x` [--explain E0382] --> <anon>:9:20 8 |> let v2 = v1; |> -- value moved here 9 |> println!("{}", v1.x); |> ^^^^ value used here after move <std macros>:2:27: 2:58: note: in this expansion of format_args! <std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>) <anon>:9:5: 9:26: note: in this expansion of println! (defined in <std macros>) note: move occurs because `v1` has type `Point`, which does not implement the `Copy` trait error: aborting due to previous error compile
  • 9. Move By Default struct Point { x: i32, y: i32 } fn main() { let v1 = Point{ x: 10, y: 20}; let v2 = v1; println!("{}", v1.x); } error: use of moved value: `v1.x` [--explain E0382] --> <anon>:9:20 8 |> let v2 = v1; |> -- value moved here 9 |> println!("{}", v1.x); |> ^^^^ value used here after move <std macros>:2:27: 2:58: note: in this expansion of format_args! <std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>) <anon>:9:5: 9:26: note: in this expansion of println! (defined in <std macros>) note: move occurs because `v1` has type `Point`, which does not implement the `Copy` trait error: aborting due to previous error compile Use of moved value! v1.x
  • 10. Move By Default stack struct Point { x: i32, y: i32 } fn main() { let v1 = Point{ x: 10, y: 20}; let v2 = v1; println!("{}", v1.x); } Point { x = 10, y = 20 } names v1
  • 11. Move By Default stack struct Point { x: i32, y: i32 } fn main() { let v1 = Point{ x: 10, y: 20}; let v2 = v1; println!("{}", v1.x); } Point { x = 10, y = 20 } names v1 v2
  • 12. Copyable Type The types which implement Copy trait can make assignment operator be copy semantics. Allow to use the variable which be copied. All primitive types implement the Copy trait.
  • 13. Copyable Type fn main() { let v1 = 10; let v2 = v1; println!("v1 = {}", v1); println!("v2 = {}", v2); } v1 = 10 v2 = 10 Program ended. run
  • 14. Copyable Type fn main() { let v1 = 10; let v2 = v1; println!("v1 = {}", v1); println!("v2 = {}", v2); } stacknames v1 i32 { 10 }
  • 15. Copyable Type fn main() { let v1 = 10; let v2 = v1; println!("v1 = {}", v1); println!("v2 = {}", v2); } stacknames v1 i32 { 10 } v2 i32 { 10 }
  • 16. Parameter Passing Passing parameters is also move semantics by default (no Copy trait). Developers should return the ownership of parameters by themselves. Yes, you should return ten variables back if you pass ten parameters into a function. 😜
  • 17. Parameter Passing struct Pt { x: i32, y: i32 } fn dist(v: Pt) -> Pt { println!("{}", v.x * v.x + v.y * v.y); v } fn main() { let v = Pt{ x: 3, y: 4 }; let v = dist(v); println!("{} {}", v.x, v.y); } struct Pt { x: i32, y: i32 } fn dot(v1: Pt, v2: Pt) -> (Pt, Pt) { println!("{}", v1.x * v2.x + v1.y * v2.y); (v1, v2) } fn main() { let v1 = Pt{ x: 3, y: 4 }; let v2 = Pt{ x: 1, y: 2 }; let (v1, v2) = dot(v1, v2); println!("{} {}", v1.x, v1.y); println!("{} {}", v2.x, v2.y); } one parameter two parameters
  • 18. Parameter Passing struct Pt { x: i32 } fn square(v: Pt) { println!("{}", v.x * v.x); } fn main() { let v = Pt{ x: 3 }; square(v); println!("{}", v.x); } error: use of moved value: `v.x` [--explain E0382] --> <anon>:10:20 9 |> square(v); |> - value moved here 10 |> println!("{}", v.x); |> ^^^ value used here after move <std macros>:2:27: 2:58: note: in this expansion of format_args! <std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>) <anon>:10:5: 10:25: note: in this expansion of println! (defined in <std macros>) note: move occurs because `v` has type `Pt`, which does not implement the `Copy` trait error: aborting due to previous error compile
  • 19. Parameter Passing struct Pt { x: i32 } fn square(v: Pt) { println!("{}", v.x * v.x); } fn main() { let v = Pt{ x: 3 }; square(v); println!("{}", v.x); } error: use of moved value: `v.x` [--explain E0382] --> <anon>:10:20 9 |> square(v); |> - value moved here 10 |> println!("{}", v.x); |> ^^^ value used here after move <std macros>:2:27: 2:58: note: in this expansion of format_args! <std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>) <anon>:10:5: 10:25: note: in this expansion of println! (defined in <std macros>) note: move occurs because `v` has type `Pt`, which does not implement the `Copy` trait error: aborting due to previous error compile v.x Use of moved value!
  • 20. 4.9 Reference and Borrowing[link]
  • 21. Syntax of Reference fn main() { let a = 1; let b = &a; // &a is the reference to a let mut c = 2; let d = &mut c; // &mut c is the mutable reference to c }
  • 22. Borrowing Use the references to borrow the ownership. The ownership will return to original owner when the borrower is destroyed automatically. References are immutable. Allow multiple references to one variable. A borrowed variable can be read but not written. Only allow to borrow the variable with longer lifetime.
  • 23. Borrowing fn main() { let orig = 0; let b1 = &orig; let b2 = &orig; let b3 = &orig; println!("b1 = {}", b1); println!("b2 = {}", b2); println!("b3 = {}", b3); println!("orig = {}", orig); } b1 = 0 b2 = 0 b3 = 0 orig = 0 Program ended. run
  • 24. Borrowing fn main() { let mut x = 0; { let y = &x; x += 1; println!("{}", y); } println!("{}", x); } error: cannot assign to `x` because it is borrowed [--explain E0506] --> <anon>:5:9 4 |> let y = &x; |> - borrow of `x` occurs here 5 |> x += 1; |> ^^^^^^ assignment to borrowed `x` occurs here error: aborting due to previous error compile
  • 25. Borrowing fn main() { let mut x = 0; { let y = &x; x += 1; println!("{}", y); } println!("{}", x); } error: cannot assign to `x` because it is borrowed [--explain E0506] --> <anon>:5:9 4 |> let y = &x; |> - borrow of `x` occurs here 5 |> x += 1; |> ^^^^^^ assignment to borrowed `x` occurs here error: aborting due to previous error compile x += 1; Cannot write the borrowed variable!
  • 26. Borrowing fn main() { let y: &i32; { let x = 5; y = &x; } println!("{}", y); } error: `x` does not live long enough --> <anon>:5:14 5 |> y = &x; |> ^ note: reference must be valid for the block suffix following statement 0 at 2:16... --> <anon>:2:17 2 |> let y: &i32; |> ^ note: ...but borrowed value is only valid for the block suffix following statement 0 at 4:18 --> <anon>:4:19 4 |> let x = 5; |> ^ error: aborting due to previous error compile
  • 27. Borrowing fn main() { let y: &i32; { let x = 5; y = &x; } println!("{}", y); } error: `x` does not live long enough --> <anon>:5:14 5 |> y = &x; |> ^ note: reference must be valid for the block suffix following statement 0 at 2:16... --> <anon>:2:17 2 |> let y: &i32; |> ^ note: ...but borrowed value is only valid for the block suffix following statement 0 at 4:18 --> <anon>:4:19 4 |> let x = 5; |> ^ error: aborting due to previous error compile y = &x; Lifetime of x is shorter than y.
  • 28. Borrowing fn main() { let y: &i32; let x = 5; y = &x; println!("{}", y); } error: `x` does not live long enough --> <anon>:4:10 4 |> y = &x; |> ^ note: reference must be valid for the block suffix following statement 0 at 2:16... --> <anon>:2:17 2 |> let y: &i32; |> ^ note: ...but borrowed value is only valid for the block suffix following statement 1 at 3:14 --> <anon>:3:15 3 |> let x = 5; |> ^ error: aborting due to previous error compile
  • 29. Borrowing fn main() { let y: &i32; let x = 5; y = &x; println!("{}", y); } error: `x` does not live long enough --> <anon>:4:10 4 |> y = &x; |> ^ note: reference must be valid for the block suffix following statement 0 at 2:16... --> <anon>:2:17 2 |> let y: &i32; |> ^ note: ...but borrowed value is only valid for the block suffix following statement 1 at 3:14 --> <anon>:3:15 3 |> let x = 5; |> ^ error: aborting due to previous error compile y = &x; Lifetime of x is shorter than y.
  • 30. Borrowing struct Pt { x: i32, y: i32 } fn dot(v1: Pt, v2: Pt) -> (Pt, Pt) { println!("{}", v1.x * v2.x + v1.y * v2.y); (v1, v2) } fn main() { let v1 = Pt{ x: 3, y: 4 }; let v2 = Pt{ x: 1, y: 2 }; let (v1, v2) = dot(v1, v2); println!("{} {}", v1.x, v1.y); println!("{} {}", v2.x, v2.y); } struct Pt { x: i32, y: i32 } fn dot(v1: &Pt, v2: &Pt) { println!("{}", v1.x * v2.x + v1.y * v2.y); } fn main() { let v1 = Pt{ x: 3, y: 4 }; let v2 = Pt{ x: 1, y: 2 }; dot(&v1, &v2); println!("{} {}", v1.x, v1.y); println!("{} {}", v2.x, v2.y); }
  • 31. Borrowing struct Pt { x: i32, y: i32 } fn dot(v1: Pt, v2: Pt) -> (Pt, Pt) { println!("{}", v1.x * v2.x + v1.y * v2.y); (v1, v2) } fn main() { let v1 = Pt{ x: 3, y: 4 }; let v2 = Pt{ x: 1, y: 2 }; let (v1, v2) = dot(v1, v2); println!("{} {}", v1.x, v1.y); println!("{} {}", v2.x, v2.y); } struct Pt { x: i32, y: i32 } fn dot(v1: &Pt, v2: &Pt) { println!("{}", v1.x * v2.x + v1.y * v2.y); } fn main() { let v1 = Pt{ x: 3, y: 4 }; let v2 = Pt{ x: 1, y: 2 }; dot(&v1, &v2); println!("{} {}", v1.x, v1.y); println!("{} {}", v2.x, v2.y); }
  • 32. Mutable Borrowing Use mutable references only if you need to change the values you borrowed. Only allow to borrow a mutable variables as a mutable reference. There is exactly one mutable reference to a variable. A variable borrowed as a mutable reference can not be borrowed as immutable references. A variable borrowed as a mutable reference can not be used until the end of borrowing.
  • 33. Mutable Borrowing fn main() { let mut x = 0; { let y = &mut x; *y += 1; } println!("x = {}", x); } x = 1 Program ended. run
  • 34. Mutable Borrowing fn main() { let mut x = 0; { let y = &mut x; let z = &mut x; *y += 1; } println!("x = {}", x); } error: cannot borrow `x` as mutable more than once at a time [--explain E0499] --> <anon>:5:22 4 |> let y = &mut x; |> - first mutable borrow occurs here 5 |> let z = &mut x; |> ^ second mutable borrow occurs here 6 |> *y += 1; 7 |> } |> - first borrow ends here error: aborting due to previous error compile
  • 35. Mutable Borrowing fn main() { let mut x = 0; { let y = &mut x; let z = &mut x; *y += 1; } println!("x = {}", x); } error: cannot borrow `x` as mutable more than once at a time [--explain E0499] --> <anon>:5:22 4 |> let y = &mut x; |> - first mutable borrow occurs here 5 |> let z = &mut x; |> ^ second mutable borrow occurs here 6 |> *y += 1; 7 |> } |> - first borrow ends here error: aborting due to previous error compile let z = &mut x; Cannot borrow x as mutable reference more than once!
  • 36. Mutable Borrowing fn main() { let mut x = 0; { let y = &mut x; let z = &x; *y += 1; } println!("x = {}", x); } error: cannot borrow `x` as immutable because it is also borrowed as mutable [--explain E0502] --> <anon>:6:18 4 |> let y = &mut x; |> - mutable borrow occurs here 5 |> *y += 1; 6 |> let z = &x; |> ^ immutable borrow occurs here 7 |> } |> - mutable borrow ends here error: aborting due to previous error compile
  • 37. Mutable Borrowing fn main() { let mut x = 0; { let y = &mut x; let z = &x; *y += 1; } println!("x = {}", x); } error: cannot borrow `x` as immutable because it is also borrowed as mutable [--explain E0502] --> <anon>:6:18 4 |> let y = &mut x; |> - mutable borrow occurs here 5 |> *y += 1; 6 |> let z = &x; |> ^ immutable borrow occurs here 7 |> } |> - mutable borrow ends here error: aborting due to previous error compile let z = &x; Cannot borrow the variable been borrowed as a mutable reference!
  • 38. Mutable Borrowing fn main() { let mut x = 0; { let y = &mut x; let z = x + 1; } println!("x = {}", x); } error: cannot use `x` because it was mutably borrowed [E0503] --> <anon>:5:17 5 |> let z = x + 1; |> ^ note: borrow of `x` occurs here --> <anon>:4:22 4 |> let y = &mut x; |> ^ error: aborting due to previous error compile
  • 39. Mutable Borrowing fn main() { let mut x = 0; { let y = &mut x; let z = x + 1; } println!("x = {}", x); } error: cannot use `x` because it was mutably borrowed [E0503] --> <anon>:5:17 5 |> let z = x + 1; |> ^ note: borrow of `x` occurs here --> <anon>:4:22 4 |> let y = &mut x; |> ^ error: aborting due to previous error compile let z = x + 1; Cannot access the variable been borrowed as a mutable reference.
  • 40. Thinking in Scopes fn main() { let mut x = 0; let y = &mut x; *y += 1; println!("x = {}", x); } Why compile error?
  • 41. Thinking in Scopes(cont’) fn main() { let mut x = 0; let y = &mut x; *y += 1; println!("x = {}", x); } error: cannot borrow `x` as immutable because it is also borrowed as mutable [--explain E0502] --> <anon>:5:24 3 |> let y = &mut x; |> - mutable borrow occurs here 4 |> *y += 1; 5 |> println!("x = {}", x); |> ^ immutable borrow occurs here 6 |> } |> - mutable borrow ends here <std macros>:2:27: 2:58: note: in this expansion of format_args! <std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>) <anon>:5:5: 5:27: note: in this expansion of println! (defined in <std macros>) error: aborting due to previous error compile
  • 42. Thinking in Scopes(cont’) fn main() { let mut x = 0; let y = &mut x; *y += 1; println!("x = {}", x); } error: cannot borrow `x` as immutable because it is also borrowed as mutable [--explain E0502] --> <anon>:5:24 3 |> let y = &mut x; |> - mutable borrow occurs here 4 |> *y += 1; 5 |> println!("x = {}", x); |> ^ immutable borrow occurs here 6 |> } |> - mutable borrow ends here <std macros>:2:27: 2:58: note: in this expansion of format_args! <std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>) <anon>:5:5: 5:27: note: in this expansion of println! (defined in <std macros>) error: aborting due to previous error compile println!("x = {}", x); Immutable borrow occurs here!
  • 43. Iterator Invalidation fn main() { let mut v = vec![1, 2, 3]; for i in &v { println!("{}", i); v.push(34); } } error: cannot borrow `v` as mutable because it is also borrowed as immutable [--explain E0502] --> <anon>:6:9 4 |> for i in &v { |> - immutable borrow occurs here 5 |> println!("{}", i); 6 |> v.push(34); |> ^ mutable borrow occurs here 7 |> } |> - immutable borrow ends here error: aborting due to previous error compile
  • 44. Iterator Invalidation fn main() { let mut v = vec![1, 2, 3]; for i in &v { println!("{}", i); v.push(34); } } error: cannot borrow `v` as mutable because it is also borrowed as immutable [--explain E0502] --> <anon>:6:9 4 |> for i in &v { |> - immutable borrow occurs here 5 |> println!("{}", i); 6 |> v.push(34); |> ^ mutable borrow occurs here 7 |> } |> - immutable borrow ends here error: aborting due to previous error compile v.push(34); push(&mut self, …) try to borrow v as a mutable reference!
  • 46. Syntax of Lifetimes Specifier fn fn2<'a>(x: &'a i32) -> &'a i32 { // do something }
  • 47. Syntax of Lifetimes Specifier fn fn2<'a>(x: &'a i32) -> &'a i32 { // do something } 'a 'a 'a input lifetime output lifetime
  • 48. Syntax of Lifetimes Specifier // lifetime with mutable reference fn foo<'a>(x: &'a mut i32) -> &'a mut i32 { // do something } // lifetime in struct struct Foo<'a> { x: &'a i32 } // lifetime with impl impl<'a> Foo<'a> { fn x(&self) -> &'a i32 { self.x } }
  • 49. Lifetimes Specifier All references need lifetimes. Explicit lifetimes are used to make lifetime inference unambiguous. Must give explicit lifetimes for struct contain reference members. No need to give explicit lifetimes to the functions without references return.
  • 50. Lifetimes Specifier struct Foo<'a> { x: &'a i32 } impl<'a> Foo<'a> { fn x(&self) -> &'a i32 { self.x } } fn main() { let y = 5; let f = Foo { x: &y }; println!("{}", f.x); println!("{}", f.x()); } 5 5 Program ended. run
  • 51. Lifetime Inference Each elided lifetime of arguments becomes a distinct lifetime parameter. If there is exactly one input lifetime, all elided lifetimes of the return values will be as same as the input lifetime. If there is &self in input lifetimes, all elided lifetimes of the return values will be as same as &self.
  • 52. Lifetime Inference (valid) fn print(s: &str); // elided fn print<'a>(s: &'a str); // expanded ////////// fn substr(s: &str, until: u32) -> &str; // elided fn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded ////////// fn get_mut(&mut self) -> &mut T; // elided fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded
  • 53. Lifetime Inference (invalid) fn get_str() -> &str; // ILLEGAL, no inputs ////////// fn frob(s: &str, t: &str) -> &str; // Two input lifetimes fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Output lifetime is ambiguous
  • 54. Static Lifetime Some resources have the lifetime of the entire program. No need to give explicit lifetime for functions return static resources.
  • 55. Lifetimes Specifier static FIVE: i32 = 5; fn get_five() -> &'static i32 { &FIVE } fn main() { let x = get_five(); println!("x = {}", x); } x = 5 Program ended. run