micanzhang / ob-rust

28 stars 10 forks source link

Using :args to pass command line arguments to the main function #11

Open phtrivier opened 1 year ago

phtrivier commented 1 year ago

I have this org file:

:PROPERTIES:
:header-args:rust: :noweb yes :comments noweb
:END:

* The program
** General structure

#+name: main
#+begin_src rust :tangle main.rs
<<imports>>
fn main() {
    <<gather-input>>
    <<count>>
}
<<tests>>
#+end_src

#+RESULTS: main
: thread 'main' panicked at 'No argument provided', src/main.rs:9:9

** Gathering input

We simply get the first parameter, panicking if there is nothing specified.

#+name: gather-input
#+begin_src rust
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
    panic!("No argument provided");
}
<<parse-input>>
#+end_src

... skipped ... 

I can run org-babel-tangle to produce a main.rs file, and things work fine when I run cargo run 3, for example.

However, I would like to provide a command line arguments to the source block, so that I can run org-babel-execute-maybe inside this block, and use a value:

#+name: main
#+begin_src rust :tangle main.rs
<<imports>>
fn main() {
    <<gather-input>>
    <<count>>
}
<<tests>>
#+end_src

I understand that I could use a default argument, etc... However, the doc in ob-rust.el says that args should work, but I could not make it work. Is there something else to do than that ?

#+name: main
#+begin_src` rust :tangle main.rs :args 3
...