iT邦幫忙

2023 iThome 鐵人賽

DAY 11
0

也有英文版文章
Also this tutorial has been written in English
Check out my Medium

Rust的中文翻譯以參考這份檔案為主.


目錄

  • 字串(Strings)

字串(Strings)

Example 01 - 2個最常用的字串型別

  • String ( 最常用 )
  • &str ( 傳到函式 )

fn print_it(data: &str) {
    println!("{:?}", data);
}

fn main() {
    print_it("A string slice");
    let owned_string = "owned string".to_owned();
    let another_string = String::from("another");

    print_it(&owned_string);
    print_it(&another_string);
}

/*
"A string slice"
"owned string"
"another"
*/

Example 02

  • 在main(),建一個陣列(在rust是Vec!),在這裡我們可以看到兩種不同的字串建立方法

struct LineItem {
    name: String,
    count: i32,
}
fn print_name(name: &str) {
    println!("name: {:?}", name);
}

fn main() {
    let receipt = vec![
        LineItem {
            name: "Apple".to_owned(),
            count: 1,
        },
        LineItem {
            name: String::from("Citrus"),
            count: 3,
        },
    ];

    for item in receipt {
        print_name(&item.name);
        println!("count: {:?}", item.count);
    }
}
/*
name: "Apple"
count: 1
name: "Citrus"
count: 3
*/

Example 03

  • 結合結構體(struct)和陣列使用方法
  • 在名字(name) & 喜愛顏色(fav_color)的部分,特別關注字串使用方法
struct Person {
    name: String,
    fav_color: String,
    age: i32,
}

fn print(data: &str) {
    println!("{:?}", data);
}

fn main() {
    let people = vec![
        Person {
            name: String::from("George"),
            fav_color: String::from("green"),
            age: 7,
        },
        Person {
            name: String::from("Anna"),
            fav_color: String::from("purple"),
            age: 9,
        },
        Person {
            name: String::from("Katie"),
            fav_color: String::from("blue"),
            age: 14,
        },
    ];

    for person in people {
        if person.age <= 10 {
            print(&person.name);
            print(&person.fav_color);
        }
    }
}

/*
"George"
"green"
"Anna"
"purple"
*/


參考資料 Reference

Nice 教學影片


上一篇
Day 10 - 向量(Vector)
下一篇
Day 12 - 派生屬性(Derive) & 參數和引數的差異(Difference between parameter and argument)
系列文
Let's go Rusty. 從0開始了解Rust.15
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言