|
ToDo:
|
これも理解しておくのです。
構造体にトレイト*1を追加してあげないとコンパイルエラーになっちゃう。
struct Color{
r: u32,
g: u32,
b: u32,
}
fn main() {
let x = Color{r :255, g: 255, b: 255};
let y = x;
println!("{:?}",y);
}
これだと
error[E0277]: the trait bound `Color: std::fmt::Debug` is not satisfied
--> src/main.rs:11:21
|
11 | println!("{:?}",y);
| ^ the trait `std::fmt::Debug` is not implemented for `Color`
|
= note: `Color` cannot be formatted using `:?`; if it is defined in your crate, add `#[derive(Debug)]` or manually implement it
= note: required by `std::fmt::Debug::fmt`
error: aborting due to previous error
だそうなのでdebug traitを追加
#[derive(Debug)]
struct Color{
r: u32,
g: u32,
b: u32,
}
fn main() {
let x = Color{r :255, g: 255, b: 255};
let y = x;
println!("{:?}",y);
}
この時点ではCopy Traitを追加してないので
#[derive(Debug)]
struct Color{
r: u32,
g: u32,
b: u32,
}
fn main() {
let x = Color{r :255, g: 255, b: 255};
let y = x;
println!("{:?}",y);
println!("{:?}",x);
}
だとコンパイルエラーです
error[E0382]: use of moved value: `x`
--> src/main.rs:12:21
|
10 | let y = x;
| - value moved here
11 | println!("{:?}",y);
12 | println!("{:?}",x);
| ^ value used here after move
|
= note: move occurs because `x` has type `Color`, which does not implement the `Copy` trait
error: aborting due to previous error
そこでCopyとClone Traitを追加してあげると通ります
#[derive(Debug,Copy,Clone)]
struct Color{
r: u32,
g: u32,
b: u32,
}
fn main() {
let x = Color{r :255, g: 255, b: 255};
let y = x;
println!("{:?}",y);
println!("{:?}",x);
}
それかyのscopeを狭めて借用を使うんですかね。
#[derive(Debug)]
struct Color{
r: u32,
g: u32,
b: u32,
}
fn main() {
let x = Color{r :255, g: 255, b: 255};
{
let y = &x;
println!("{:?}",y);
}
println!("{:?}",x);
}
*1 特性