Categories
Tags
algorithms APIT arm assembly asynchronous base64 Blogging box c clang-format cmake compiler concurrency const_fn contravariant cos covariant cpp Customization cybersecurity DataStructure db Demo deserialization discrete doc DP Dynamic Example FFI flat_map FP Functional functions futures Fuwari GATs gccrs generics gitignore GUI hacking hashmap haskell heap interop invariant iterator justfile kernel LaTeX LFU linux MachineLearning Markdown math ML OnceLock optimization OS parallels perf physics pin postgresql release RPIT rust science Science serialization shift sin SmallProjects std String surrealdb swisstable synchronous tan traits triangulation utf16 utf8 Video x86_64 xilem zig
248 words
1 minutes
260107_traits04_clone_copy
Clone 구현하기
derive macro를 써서 손 쉽게 구현
error code
- OwnerShip(오너쉽) 위반으로 실행 되지 않는다.
struct Young {
data: String,
}
fn main() {
let my_data = Young {
data: "test".to_string(),
};
let my_data_clone = my_data;
println!("my_data : {:?}", my_data);
}cargo r을 하게 되면 러스트가 Clone을 구현하라고 에러메세지를 알려준다.
consider implementing `Clone` for this type
...
복잡한 타입일수록 내가 구현해줘야한다.
derive macro를 써서 날로 먹어도 되고
#[derive(Debug, Clone)]
struct Young {
data: String,
}
fn main() {
let my_data = Young {
data: "test".to_string(),
};
let my_data_clone = my_data.clone();
println!("my_data : {:?}", my_data);
}Clone을 구현해 보자- 코드가 복잡할 수록 내가 구현 할줄 알아야한다.
- Rust 는 Zero Cost Abstraction이라는 것만 기억하면된다.
- 등가교환이다. 꽁짜는 없다.
#[derive(Debug)]
struct Young {
data: String,
}
impl Clone for Young {
fn clone(&self) -> Self {
Self {
data: self.data.clone(),
}
}
}
fn main() {
let my_data = Young {
data: "test".to_string(),
};
let my_data_clone = my_data.clone();
println!("my_data : {:?}", my_data);
}260107_traits04_clone_copy
https://younghakim7.github.io/blog/posts/260107_traits04_clone_copy/