
    
        
        
        
                
        
        
        
                
        
        
        
            
{"version":"https:\/\/jsonfeed.org\/version\/1","title":"mathspp.com feed","home_page_url":"https:\/\/mathspp.com\/blog\/tags\/rust","feed_url":"https:\/\/mathspp.com\/blog\/tags\/rust.json","description":"Stay up-to-date with the articles on mathematics and programming that get published to mathspp.com.","author":{"name":"Rodrigo Gir\u00e3o Serr\u00e3o"},"items":[{"title":"TIL #070 \u2013 writing and running tests in Rust","date_published":"2023-07-18T12:00:00+02:00","id":"https:\/\/mathspp.com\/blog\/til\/writing-and-running-tests-in-rust","url":"https:\/\/mathspp.com\/blog\/til\/writing-and-running-tests-in-rust","content_html":"<p>Today I learned how to write and run tests in the Rust programming language.<\/p>\n\n<h2 id=\"writing-a-test-in-rust\">Writing a test in Rust<a href=\"#writing-a-test-in-rust\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>I'm attending <a href=\"https:\/\/ep2023.europython.eu\/session\/write-your-first-web-api-with-rust\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">a Rust tutorial at EuroPython 2023<\/a> and I just learned how to write and run tests in Rust.\nTurns out it is quite straightforward!<\/p>\n<div class=\"notices yellow\">\n<p>I'm a Rust beginner!\nI don't know if there are other ways of writing tests, possibly more advanced and\/or more flexible.\nWhat I'm showing is just a simple way of creating tests.<\/p>\n<\/div>\n<p>Suppose you have a function that determines whether or not a given age corresponds to an adult age in Europe (or, at least, most European countries):<\/p>\n<pre><code class=\"language-rust\">fn is_adult(age: u8) -&gt; bool {\n    age &gt;= 18\n}<\/code><\/pre>\n<p>In order to test this function, you create test functions (like you do in <code>pytest<\/code>, for example).\nIn <code>pytest<\/code>, a function is a test function whenever its name starts with <code>test_<\/code>.\nIn Rust, if you add a <code>#[test]<\/code> at the top of the function definition, that function is now a test function.<\/p>\n<p>Then, similarly to how the keyword <code>assert<\/code> works in Python, you can use the macro <code>assert!<\/code> to check for the test result in Rust.<\/p>\n<p>Here are a couple of tests for the function <code>is_adult<\/code>, above:<\/p>\n<pre><code class=\"language-rust\">#[test]\nfn is_adult_is_true_for_adults() {\n    assert!(is_adult(18));\n    assert!(is_adult(19));\n    assert!(is_adult(123));\n}\n\n#[test]\nfn is_adult_is_false_for_kids() {\n    assert!( !is_adult(1) );\n    assert!( !is_adult(17) );\n}<\/code><\/pre>\n<p>The macro <code>assert!<\/code> expects a Boolean value and it will fail if the Boolean is <code>false<\/code>.<\/p>\n<p>I know that there is, <em>at least<\/em>, one other assertion macro in Rust.\n<code>assert_eq!<\/code> takes two values, compares them, and if they differ, the test fails.<\/p>\n<p>Your whole file could look like this:<\/p>\n<pre><code class=\"language-rust\">fn is_adult(age: u8) -&gt; bool {\n    age &gt;= 18\n}\n\nfn main() {\n    println!(\"What's up?\");\n}\n\n#[test]\nfn is_adult_is_true_for_adults() {\n    assert!(is_adult(18));\n    assert!(is_adult(19));\n    assert!(is_adult(123));\n}\n\n#[test]\nfn is_adult_is_false_for_kids() {\n    assert!( !is_adult(1) );\n    assert!( !is_adult(17) );\n}<\/code><\/pre>\n<h2 id=\"how-to-run-your-rust-tests\">How to run your Rust tests<a href=\"#how-to-run-your-rust-tests\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>To run your Rust tests, you just use the command <code>cargo test<\/code>.\nThat's it!\nIf you do, you should get output like this:<\/p>\n<figure class=\"image-caption\"><img title=\"Output of running Rust tests.\" alt=\"Command line output of running Rust tests with the command `cargo test`.\" src=\"\/user\/pages\/02.blog\/04.til\/070.writing-and-running-tests-in-rust\/_test_output.webp\"><figcaption class=\"\">Output of running Rust tests.<\/figcaption><\/figure>\n<p>That's it for now! <a href=\"\/subscribe\">Stay tuned<\/a> and I'll see you around!<\/p>","summary":"Today I learned how to write and run tests in the Rust programming language.","date_modified":"2025-07-23T16:49:02+02:00","tags":["programming","rust"],"image":"\/user\/pages\/02.blog\/04.til\/070.writing-and-running-tests-in-rust\/thumbnail.webp"},{"title":"TIL #062 \u2013 dbg! macro for debugging in Rust","date_published":"2023-05-05T00:00:00+02:00","id":"https:\/\/mathspp.com\/blog\/til\/dbg%21-macro-for-debugging-in-rust","url":"https:\/\/mathspp.com\/blog\/til\/dbg%21-macro-for-debugging-in-rust","content_html":"<p>Today I learned why I should use the <code>dbg!<\/code> macro instead of the <code>println!<\/code> macro for debugging in Rust.<\/p>\n\n<h2 id=\"what-is-the-dbg-macro-in-rust\">What is the <code>dbg!<\/code> macro in Rust?<a href=\"#what-is-the-dbg-macro-in-rust\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>The <code>dgb!<\/code> macro is a macro that is similar to <code>println!<\/code> but that is designed specifically for debugging.\nNot only does it print the values you pass it, but it also adds a tag with the name of the file and the line from where the macro was called.<\/p>\n<p>Here is an example of using the <code>dbg!<\/code> macro:<\/p>\n<pre><code class=\"language-rust\">fn main() {\n    dbg!(\"hello, world!\");\n}<\/code><\/pre>\n<p>If you run your program with <code>cargo run<\/code> now, this is what you get:<\/p>\n<pre><code class=\"language-bash\">\u276f cargo run\n   Compiling borrowing v0.1.0 (\/Users\/rodrigogs\/Documents\/rust\/borrowing)\n    Finished dev [unoptimized + debuginfo] target(s) in 0.10s\n     Running `target\/debug\/borrowing`\n[src\/main.rs:2] \"hello, world\" = \"hello, world\"<\/code><\/pre>\n<p>Notice the last line of the output, that shows the argument to the macro, along with the line of code from where the macro was called.\nIt may look redundant to have <code>\"hello, world\" = \"hello, world\"<\/code> displayed there, but that is because the macro will show the expression that was used as its argument <em>and<\/em> it will show the value of that expression.<\/p>\n<p>Here is another example program:<\/p>\n<pre><code class=\"language-rust\">fn main() {\n    dbg!(3 + 3);\n}<\/code><\/pre>\n<p>This shows:<\/p>\n<pre><code class=\"language-bash\">\u276f cargo run\n## ...\n[src\/main.rs:2] 3 + 3 = 6<\/code><\/pre>\n<p>Or this program:<\/p>\n<pre><code class=\"language-rust\">fn main() {\n    let x = 3;\n    dbg!(x);\n}<\/code><\/pre>\n<p>Shows:<\/p>\n<pre><code class=\"language-bash\">\u276f cargo run\n## ...\n[src\/main.rs:3] x = 3<\/code><\/pre>\n<p>So, this is how you use the <code>dbg!<\/code> macro in Rust!<\/p>\n<p>That's it for now! <a href=\"\/subscribe\">Stay tuned<\/a> and I'll see you around!<\/p>","summary":"Today I learned why I should use the `dbg!` macro instead of the `println!` macro for debugging in Rust.","date_modified":"2025-07-23T16:49:02+02:00","tags":["programming","rust"],"image":"\/user\/pages\/02.blog\/04.til\/062.dbg!-macro-for-debugging-in-rust\/thumbnail.webp"},{"title":"Write a Python module in Rust","date_published":"2023-05-03T00:00:00+02:00","id":"https:\/\/mathspp.com\/blog\/write-a-python-module-in-rust","url":"https:\/\/mathspp.com\/blog\/write-a-python-module-in-rust","content_html":"<p>Learn how to write your first Python module in Rust.<\/p>\n\n<p><img alt=\"\" src=\"\/user\/pages\/02.blog\/write-a-python-module-in-rust\/thumbnail.webp\"><\/p>\n<h2 id=\"introduction\">Introduction<a href=\"#introduction\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>I'm not going to open with a long-winded introduction explaining why Rust is so awesome and great.\nI don't know if it is or not.\nI just hear a lot about Rust and I wanted to try and write a Python module in Rust.\nSo, I did!<\/p>\n<h2 id=\"set-up\">Set up<a href=\"#set-up\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>To follow this tutorial, you need to start by installing Rust.\nYou can head over to <a href=\"https:\/\/www.rust-lang.org\/tools\/install\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">rust-lang.org<\/a> and follow the installation instructions there.<\/p>\n<p>Then, we'll use PyO3 to bind Python and Rust together.\nTo make our lives easier, we set everything up through maturin, which I understand simplifies the process a bit.<\/p>\n<p>Start by creating a virtual environment in a folder for this project:<\/p>\n<pre><code class=\"language-bash\">$ mkdir rust-factorial\n$ cd rust-factorial\n$ python -m venv .env\n$ source .env\/bin\/activate  # Activate the virtual env.\n$ pip install maturin<\/code><\/pre>\n<p>After installing maturin, we use the command <code>maturin init<\/code> to create a project.\nWhen asked for it, select the <code>pyo3<\/code> bindings!<\/p>\n<p>Maturin will go ahead and create a couple of files for you.\nThey'll contain a simple, working example of a Python module written in Rust.<\/p>\n<p>You can actually see it already works by running the command <code>maturin develop<\/code> and then using the module from Python:<\/p>\n<pre><code class=\"language-bash\">$ maturin develop\n## lots of progress output as maturin runs the compilation...\n$ python\n&gt;&gt;&gt; import rust_factorial\n&gt;&gt;&gt; rust_factorial.sum_as_string(5, 20)\n'25'<\/code><\/pre>\n<p>Now, let us write our own Rust code.<\/p>\n<h2 id=\"a-factorial-function-in-rust\">A factorial function in Rust<a href=\"#a-factorial-function-in-rust\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>As my first attempt at writing some Rust code, I decided to write the factorial function.\nBetween some educated guesses and compiler errors, I managed to put this together:<\/p>\n<pre><code class=\"language-rs\">fn factorial(n: u128) -&gt; u128 {\n    if n &lt;= 1 {\n        return n\n    } else {\n        return n * factorial(n - 1)\n    }\n}<\/code><\/pre>\n<p>This is the base Rust code I used.<\/p>\n<p>Then, I need to fit this into the file <code>lib.rs<\/code> that maturin created for me:<\/p>\n<pre><code class=\"language-rs\">use pyo3::prelude::*;\n\n\/\/\/ Formats the sum of two numbers as string.\n#[pyfunction]\nfn sum_as_string(a: usize, b: usize) -&gt; PyResult&lt;String&gt; {\n    Ok((a + b).to_string())\n}\n\n\/\/\/ A Python module implemented in Rust.\n#[pymodule]\nfn rust_factorial(_py: Python, m: &amp;PyModule) -&gt; PyResult&lt;()&gt; {\n    m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;\n    Ok(())\n}<\/code><\/pre>\n<p>The function <code>factorial<\/code> is going to replace the function <code>sum_as_string<\/code>, so it looks like it takes some arguments and then it needs to return a data type that is compatible with Python.\nThat's what I gather from the <code>PyResult&lt;String&gt;<\/code> result.<\/p>\n<p>The <a href=\"https:\/\/pyo3.rs\/v0.18.0\/conversions\/tables\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">PyO3 documentation<\/a> tells me I can use Rust integer types inside the <code>PyResult<\/code>, so I tried this:<\/p>\n<pre><code class=\"language-rs\">use pyo3::prelude::*;\n\nfn factorial(n: u128) -&gt; PyResult&lt;u128&gt; {\n    if n &lt;= 1 {\n        Ok(n)\n    } else {\n        Ok(n * factorial(n - 1))\n    }\n}\n\n#[pymodule]\nfn rust_factorial(_py: Python, m: &amp;PyModule) -&gt; PyResult&lt;()&gt; {\n    m.add_function(wrap_pyfunction!(factorial, m)?)?;\n    Ok(())\n}<\/code><\/pre>\n<p>Now, this gives me errors, because the recursive function is trying to multiply a regular Rust integer with the <code>PyResult<\/code> thing, so I actually added my original, 100% Rust function as <code>_factorial<\/code>, and then...<\/p>","summary":"Learn how to write your first Python module in Rust.","date_modified":"2025-07-23T16:49:02+02:00","tags":["programming","python","rust"],"image":"\/user\/pages\/02.blog\/write-a-python-module-in-rust\/thumbnail.webp"}]}
