Quine in Rust

Published on 05 April 2023 (Updated: 06 April 2023)

Welcome to the Quine in Rust page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

fn main(){println!("fn main(){{println!({0:?},{0:?})}}","fn main(){{println!({0:?},{0:?})}}")}

Quine in Rust was written by:

This article was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

Let's break this down. In Rust, the println! function displays the desired text with a newline. The first argument of println! is either an ordinary string or a format string. If it is a format string, the subsequent arguments are values to be formatted. Format strings in Rust are rather complex and powerful. If you want to learn more about this, see the official Rust documentation.

Let's take at look at this particular one:


You'll notice that both the format string and the value to be formatted are identical:

"fn main(){{println!({0:?},{0:?})}}"

In other words, we're using the format string to format itself! Notice that these characters are used in this format string:

These display like this, respectively:

The braces have to be doubled up since, as mentioned above, all format string are enclosed in braces.

Notice that the left side of that string is this:

fn main(){{println!(

That corresponds to the left-hand side of the program. The right-hand side of that string is this:


That corresponds to the right-hand side of the program. If you put this all together, you will get this output:

fn main(){println!("fn main(){{println!({0:?},{0:?})}}","fn main(){{println!({0:?},{0:?})}}")}

This is the same as the program. How cool is that?!

Anyway, I have to give credit where credit is due. I am a Rust newbie, and I would be hard-pressed to come up with this on my own. I got this code here; scroll down the Rust implementation. However, I learned a lot from this, and now I truly understand it after writing this article.

How to Run the Solution

If you want to run this program, you'll first need to download a copy of the Rust compiler, and follow the installation instructions. From there, open a terminal, and run this command:

rustc quine.rs