LoginSignup
0
0

More than 1 year has passed since last update.

The Rust Programming Language 日本語版 メモ

Posted at

戻り値とスコープ

fn main() {
  let s1 = gives_ownership();

  print!("{}", s1); // hello

  let s2 = String::from("hello");

  let s3 = takes_and_gives_back(s2);
  print!("{}", s3); // hello

  // error[E0382]: borrow of moved value: `s2`
  print!("{}", s2);
}

fn gives_ownership() -> String {
  let some_string = String::from("hello");
  some_string
}

fn takes_and_gives_back(a_string: String) -> String {
  a_string
}
fn main() {
    let s1 = String::from("hello");

    let (s2, len) = calculate_length(s1);

    // The length of 'hello' is 5.
    println!("The length of '{}' is {}.", s2, len);
}

fn calculate_length(s: String) -> (String, usize) {
    let length = s.len();

    (s, length)
}
fn main() {
  let s1 = String::from("hello");

  // error[E0308]: mismatched types
  let len = calculate_length(s1);

  println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
  s.len()
}
fn main() {
    let s1 = String::from("hello");

    let len = calculate_length(&s1);

    // The length of 'hello' is 5.
    println!("The length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0