0Pricing
Learn Rust Coding · レッスン

Stringと&strの違い

テキストの所有権

「Stringと&strの違い」はCoddyKit上の無料Learn Rust Codingレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはLearn Rust Coding学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Learn Rust Codingコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Owned vs Borrowed Text

Rust separates text ownership into two types:

  • String — owns its data on the heap.
  • &str — borrows a view of text it does not own.
fn main() {
    let owned = String::from("I own this");
    let borrowed: &str = "I am borrowed";
    println!("{} / {}", owned, borrowed);
}

Where the Data Lives

A String stores its bytes on the heap and can grow. A string literal &str is baked into the program binary and is fixed.

fn main() {
    let mut heap = String::from("grows");
    heap.push_str(" bigger");
    let fixed = "never changes";
    println!("{} | {}", heap, fixed);
}

Ownership Means Responsibility

The owner of a String frees its memory when it goes out of scope. A &str owns nothing, so it never frees anything.

fn main() {
    {
        let s = String::from("temporary");
        println!("{}", s);
    } // s is dropped and its memory freed here
    println!("done");
}

Borrowing a String

You can borrow a String as a &str using &. The String still owns the data; the slice just looks at it.

fn main() {
    let owned = String::from("shared text");
    let view: &str = &owned;
    println!("{} / {}", owned, view);
}

Moving a String

Assigning a String to another variable moves ownership. The original can no longer be used.

fn main() {
    let a = String::from("hello");
    let b = a; // ownership moves to b
    // println!("{}", a); // would error: a was moved
    println!("{}", b);
}

Cloning to Keep Both

If you need two independent owned strings, use clone to copy the data.

fn main() {
    let a = String::from("hello");
    let b = a.clone();
    println!("{} and {}", a, b);
}

Copying a &str Is Cheap

A &str is just a pointer and length, so copying it does not copy the underlying text. It implements Copy.

fn main() {
    let original = "data";
    let copy = original; // both still valid
    println!("{} {}", original, copy);
}

Functions and Ownership

Passing a String by value moves it into the function. Passing &str or &String only borrows, leaving the caller's value usable.

fn length(s: &str) -> usize {
    s.len()
}

fn main() {
    let text = String::from("measure me");
    println!("{}", length(&text));
    println!("still here: {}", text);
}

Returning Owned Strings

When a function must produce new text, it returns an owned String so the caller takes ownership.

fn make_greeting(name: &str) -> String {
    format!("Hello, {}!", name)
}

fn main() {
    let g = make_greeting("Rust");
    println!("{}", g);
}

Choosing the Right Type

Guidelines:

  • Store owned text? Use String.
  • Just read or pass text? Accept &str.
  • Build new text in a function? Return String.
fn first_word(s: &str) -> &str {
    s.split_whitespace().next().unwrap_or("")
}

fn main() {
    let sentence = String::from("learn rust today");
    println!("{}", first_word(&sentence));
}

Why the Distinction Matters

This split lets Rust avoid unnecessary copies and guarantees memory safety without a garbage collector. You always know who owns a piece of text.

fn main() {
    let owned = String::from("safe");
    let borrowed = &owned[..];
    println!("owner {} borrows {}", owned, borrowed);
}

Quick Check

Recall what happens when you move a String.

Recap

String vs &str ownership:

  • String owns heap data and frees it on drop.
  • &str borrows existing text and owns nothing.
  • Moving a String invalidates the original; clone copies it.
  • Accept &str to read, return String to produce new text.
fn shout(s: &str) -> String {
    s.to_uppercase()
}

fn main() {
    let name = String::from("rust");
    let loud = shout(&name);
    println!("{} -> {}", name, loud);
}

よくある質問

「Stringと&strの違い」レッスンは無料ですか?

はい。「Stringと&strの違い」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Learn Rust Codingコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Learn Rust Codingコースには全4レッスンが含まれています。

「Stringと&strの違い」で何を学びますか?

テキストの所有権 ブラウザで直接実行するハンズオンコードでLearn Rust Codingを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Learn Rust Codingを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのLearn Rust Codingは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「Stringと&strの違い」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このLearn Rust Codingレッスンでコードを書いて実行できますか?

はい。すべてのLearn Rust Codingレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. Stringと&strの違い
  2. スライス
  3. Stringのメソッド
  4. UTF-8とChars
← Learn Rust Codingに戻る