戻り値
2022/2/17 22:09:00
fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
}
}
https://doc.rust-jp.rs/book-ja/ch10-02-traits.html#トレイトを実装している型を返す
Copy
特質を持たない変数を関数に渡すと、所有権の移動が発生し、関数に渡した変数は使用不可能になる。
fn main() {
let s = String::from("hello");
test(s);
println!("{}", s); //error
/*
error[E0382]: borrow of moved value: `s`
--> src\main.rs:4:20
|
2 | let s = String::from("hello");
| - move occurs because `s` has type `String`, which does not implement the `Copy` trait
3 | test(s);
| - value moved here
4 | println!("{}", s); //error
| ^ value borrowed here after move
*/
}
fn test(s:String) {
println!("{}", s); //hello
}
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}
error[E0106]: missing lifetime specifier
--> src\main.rs:5:16
|
5 | fn dangle() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime
|
5 | fn dangle() -> &'static String {
| ~~~~~~~~
関数に変数を渡すことによって所有権の移動が発生するが、戻り値によっても所有権の移動が発生する。
fn main() {
let s1 = String::from("hello");
let s2 = test(s1);
println!("{}", s2); //hello
}
fn test(s:String) -> String {
s
}