Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add strings and print them?

Tags:

rust

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?

like image 542
Jan Avatar asked Apr 05 '15 15:04

Jan


People also ask

How do I print a string?

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.

How do you add up strings?

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.

How do you add strings in Python?

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.


1 Answers

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:

  • println! error: expected a literal / format argument must be a string literal
  • How do I concatenate strings?
like image 181
Shepmaster Avatar answered Jan 01 '23 06:01

Shepmaster