String vs &str in Rust

发布时间 2023-09-25 10:53:57作者: ImreW

Most likely, soon after you’ve started your Rust journey, you ran into this scenario where you tried to work with string types (or should I say, you thought you were?), and the compiler refused to compile your code because of something that looks like a string, actually isn’t a string.

当你开始Rust的学习之旅后,很可能遇到需要使用字符串的场景,但是编译器却无法让你的代码通过编译,因为有一部分代码,看起来像字符串,事实上却又不是。

For example, let’s take a look at this super simple function greet(name: String) which takes something of type String and prints it to screen using the println!() macro:

例如,让我们看看下面这个简单的函数greet(name: String),这个函数接收一个String类型的参数,然后使用println!()这个宏将它打印到屏幕上: