I am currently learning Rust (mostly from scratch) and now I want to add two strings together and print them out. But that is not as easy as in other languages. Here's what I've done so far (also tested with print!
):
fn sayHello(id: str, msg: str) {
println!(id + msg);
}
fn main() {
sayHello("[info]", "this is rust!");
}
The error I get is a little bit weird.
error: expected a literal
--> src/main.rs:2:14
|
2 | println!(id + msg);
| ^^^^^^^^
How can I solve this so that [info] this is rust will be printed out?
We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
Python add strings with + operator The easiest way of concatenating strings is to use the + or the += operator. The + operator is used both for adding numbers and strings; in programming we say that the operator is overloaded. Two strings are added using the + operator.
Don't try to learn Rust without first reading the free book The Rust Programming Language and writing code alongside.
For example, you are trying to use str
, which is an unsized type. You are also trying to pass a variable to println!
, which requires a format string. These things are covered early in the documentation because they trip so many people up. Please make use of the hard work the Rust community has done to document these things!
All that said, here's your code working:
fn say_hello(id: &str, msg: &str) {
println!("{}{}", id, msg);
}
fn main() {
say_hello("[info]", "this is Rust!");
}
I also changed to use snake_case
(the Rust style).
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With