In Rust, how do I concatenate one String with a linefeed and then another String?

mrossini

I have two variables, each containing a string. I want to concatenate both with a linefeed in between them. How do I do that?

Simon Whitehead

There are a couple of ways.

The nicest I have seen is using the join method on an array:

fn main() {
    let a = "Hello";
    let b = "world";
    let result = [a, b].join("\n");

    print!("{}", result);
}

Depending on your use case you might also prefer more control:

fn main() {
    let a = "Hello";
    let b = "world";
    let result = format!("{}\n{}", a, b);

    print!("{}", result);
}

There are some more manual ways (some of which I believe avoid any allocations at all) but I prefer the above two.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I split a linefeed delimited string in awk and use its output on the same command line in bash?

How do I copy characters from one string to another string?

How do I concatenate an escape to a string?

How do I concatenate a string with a variable?

How do I concatenate a boolean to a string in Python?

How do I concatenate a boolean to a string in Python?

How do I concatenate a string in handlebars view

How do I concatenate string and an integer?

How do I remove a single trailing string from another string in Rust?

How do I check if a given Python string is a substring of another one?

How do I append one string to another in Python?

How do I transfer certain characters from one string to another?

How do I confirm that one string sequence is a subset of another?

In Rust, how do I combine two functions that are identical, but one takes &Vec<String> and the other takes &Vec<&String>?

How to concatenate / append a string to another one in Jekyll / Liquid?

Swift: how do I concatenate a [[String]] to a [String] the right way?

How do I split a string in Rust?

How do I treat a String as a File in Rust?

How do I convert a String to an integer in Rust?

How do I convert a string to hex in Rust?

Should Rust give an error with this one liner to concatenate a new string to another using push_str()?

How to concatenate "$@" or array to one string

How can I concatenate a string with a variable and use it as another variable?

Concatenate part of the string from one column to another

Concatenate one string to another with removing duplicated part

How do I concatenate two slices in Rust?

Given two strings, how do I assign the shorter string to one variable and the longer string to another

How do I replace part of a string from one cell from a string in another cell?

How do I subtract one character from another in Rust?