/* Test for str and string*/pubfnstr_string() {let a ="It's a str";let b =String::from("It's a string");let () = a;let () = b;}/*error[E0308]: mismatched types --> src/string/str_string.rs:5:9 | 5 | let () = a; | ^^ expected str, found () | = note: expected type `str` found type `()` error[E0308]: mismatched types --> src/string/str_string.rs:6:9 | 6 | let () = b; | ^^ expected struct `std::string::String`, found () | = note: expected type `std::string::String` found type `()` */
使用内部模块时,可以创建相应的模块文件夹,然后创建mod.rs文件,使用pub mod module_name将需要外部使用的pub函数或者方法,导出。注意使用是需要使用mod crate::module::part,将每一个小模块模块化,然后可以调用其中的函数。
pubfnstring_test() {println!("Just a simple usage of String");println!("3 methods to initialize a String:");println!("str.to_string(), String.from(str), str.into()");let origin ="Hello, it's the origin str";letmut str1 =String::from(origin);let str2:String= origin.into();let str3 = origin.to_string(); str1.push_str(", and the mutable str is me!");println!("{}, {}, {}", str1, str2, str3);}/*Just a simple usage of String3 methods to initialize a String:str.to_string(), String.from(str), str.into()Hello, it's the origin str, and the mutable str is me!, Hello, it's the origin str, Hello, it's the origin str*/
关于内存的释放,Rust使用了不同的策略,当变量离开作用域时,其拥有的内存内存就被释放。rust使用了一个特殊的函数,当一个变量离开作用域时,使用drop函数(在c++中这种item在生命周期结束时释放资源的模式叫做资源获取即初始化(Resource Acquisition Is Initialization))。
let s1 =String::from("hello");let s2 = s1;/*error[E0382]: borrow of moved value: `str1` --> src/string/str_string.rs:33:38 | 32 | let str2 = str1; | ---- value moved here 33 | println!("{}, {}, {}, {}", x, y, str1, str2); | ^^^^ value borrowed here after move | = note: move occurs because `str1` has type `std::string::String`, which does not implement the `Copy` trait*/
error[E0499]: cannot borrow `s` as mutable more than once at a time --> src/string/str_string.rs:42:14|41|let s1 =&mut s; |------ first mutable borrow occurs here 42|let s2 =&mut s; |^^^^^^ second mutable borrow occurs here 43|println!("{}{}", s1, s2); |-- first borrow later used here
fnmain() {let reference_to_nothing =dangle();}fndangle() ->&String {let s =String::from("hello");&s}/*error[E0106]: missing lifetime specifier --> main.rs:5:16 |5 | fn dangle() -> &String { | ^ expected 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 giving it a 'static lifetime*/