Rust中字符串和所有权

起因

主要是学习Rust中字符串和所有权.在项目中字符串使用次数是特别频繁的。至于所有权这个和其他常用编程语言不一样的地方。

mut关键字

let x = 64;
x = 128;       //修改变量x的值,在Rust中是无法编译通过
println!("{:?}", x);

看Rust编译提示:

305 |     let x = 64;
    |         -
    |         |
    |         first assignment to `x`
    |         help: make this binding mutable: `mut x`
306 |     x = 128;
    |     ^^^^^^^ cannot assign twice to immutable variable

在Rust中,默认变量是无法进行修改的.根据提示在变量x前面加上mut关键字,在编译试试是可以通过的。

String常用的方法

fn string_test() {
    let mut str = String::from("中文");
    println!("str len = {}", str.len()); //长度为什么不是2,是因为utf-8编码,一个字符占用3个字节

    println!("str count = {}", str.chars().count()); //count是用来获取字符串长度
    let mut s = String::new();
    s.push_str("hello");
    s.push_str(" world");

    println!("{:?}", s);
    let pos = s.find('w').unwrap_or(s.len());        //查找w在字符串中的位置
    println!("{:?}", pos);

    s += " 123";             //字符串拼接
    println!("{:?}", s);

    println!("point address:{:p}", s.as_ptr()); //获取字符串的指针
    s = s.replace("w", ""); //替换
    println!("{:?}", s);
    println!("{:?}", s.contains('d')); //是否包含
}

学习一下 所有权 这个知识点

说到所有权这个概念,要先说编程语言发展史,得从c语言开始,后边c++的出现,在后来Java和C#(CSharp)出现,及Go,最后就是本篇的Rust语言.
说到编程语言,少不了这两个 栈 和 堆,有时候直接说堆栈,c和c++


秋风 2019-10-25