Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In what cases is Nim a better option than Rust? Would be great if anyone with more experience can share more information.


The relative simplicity of the language is a feature. I can imagine introducing Nim to embedded/microcontroller firmware developers that only know/use C99 now. I cannot imagine introducing Rust - while a great language, it is C++ level complexity - and that is not always warranted.


Nim fits great on microcontrollers! Benefit is that it compiles to C and therefore can run anywhere C can. It also lets you reuse all the rest of the embedded C environment and build tools, which given the nature of embedded toolchains is handy for hitting the ground running. Rust's standard library/runtime binaries are really heavy compared to Nim's.


How are your esp32 Nim deployments holding up? Do you have futur plans for the new esp32 riscv processors?


> How are your esp32 Nim deployments holding up?

They're doing great! Nim has proven surprisingly stable, which was a fear I had at first. The core team has improved compiler support and I've not run into any issues updating so far. It bolster's my confidence in Nim.

Even if Nim development were to suddenly "stop" tomorrow, it'd easily be useable for embedded for a decade or more. There's improvement to be made in Nim, but it's a resilient system design. If the same were to happen to Rust or Crystal, for example, you'd have issues keeping the compiler up to date with LLVM, etc. Compiling to C gives a lot of stability for embedded work. Sort of similar to how Delphi Pascal is still useable today.

One surprise came when I had to do some optimizations and went from `-d:debug` to `-d:release`. The debug code added enough overhead it fixed some timing issues with the high end ADC we're using. Moving to release mode made it too fast and required adding the required delay (it was in the ADC datasheet but forgot it). Easy to solve, but it's worth noting.

> Do you have futur plans for the new esp32 riscv processors?

If a risc-v processor supports C, then it already supports Nim! The real question is libraries and/or build support for the target. An afternoon of work can get the Nim build setup to work with almost any C/C++ build system. Really, Nim on risc-v just requires a target board and someone to sit down for a few hours. It's a fun "hacking exercise" :-)

As a side tangent, I'd like to make a first class "pure" FreeRTOS library as it's the most widely used RTOS. That's after dealing with a lot of annoying race conditions in the `esp-idf` and seeing the incredible amount of hacky C code in embedded systems.

Building on FreeRTOS but introducing esp32-like libraries for vfat/files/networking/etc that'd work across microcontrollers would make for an incredibly productive environment (for embedded work).

There's also the possibility of using DrNim [1] to add formal verification for certain algorithms! Nim's effect system is very flexible. Really useful would be using the "guards and locks" [2] to write and prevent deadlocks (and maybe avoid locks?) when writing resource management and device drivers. A lot of the esp-idf issue I've run into are race conditions or slow speed since even `echo`/`printf` must have a lock to protect the system UART. Those are open questions/problems, and I'm starting a new job next month so it depends on what the needs there end up being.

1: https://nim-lang.org/docs/drnim.html 2: https://nim-lang.org/docs/manual_experimental.html#guards-an...


That’s very insightful. Thank you. Some more questions since you are the person which shows up for esp32 and nim in the whole wide world :)

Did you try out the esp-idf 4.3 release yet? I think you mentioned somewhere to not use 4.2. but 4.3 gives you the esp-managed Mqtt service on Aws (rainmaker)

Do you have any thoughts on Freertos vs Zephyr whilst using Nim?


> That’s very insightful. Thank you. Some more questions since you are the person which shows up for esp32 and nim in the whole wide world :)

You're welcome. lol, no one else did it so there you are.

> Did you try out the esp-idf 4.3 release yet?

No, my work requires stability so I haven't tried any of the new esp-idf releases. Nesper does compile with 4.2 if you pass the flag for it, but it's not well tested. If none of the major API's have changed 4.3 should work.

It would be good to wrap the mqtt aws service. Don't know if I'll have time for it though. But it's really not too hard to wrap using `c2nim` on the header files. PR's welcome! :-)

> Do you have any thoughts on Freertos vs Zephyr whilst using Nim?

I would like to try Zephyr sometime. FreeRTOS is used by AWS and the esp32 so it seemed a good start.


Nim natively supports 64bit RISC-V since years and 32bit in the current devel.

Also, the compiler itself is built for rv64 in Debian.


I think the main difference (benefit?) is that Nim has the convenience of a garbage collected language while retaining good and predictable performance (e.g. via ARC/ORC and thread-local GC). Rust has no GC so requires more from the programmer. Personally, I'd rather use a GC language to have less complexity in the code even though I have to spend some more time learning to use the GC correctly.


For normal purposes, dealing with Rust's lifetimes will be easier than spending some time "learning to use the GC correctly"


Nim's ARC thing is pretty different from blackbox GCs you have to poke with a stick like Go's or JVM's. It's pretty deterministic where additional calls are inserted by the compiler, and you can use --expandArc or look at the generated C.

As a single anecdote -- I've studied Rust before and it's been a while. Pretty familiar with C++ move semantics stuff. I decided to read the Rust book again while also learning Nim simultaneously; and I had an entt wrapper and graphics rendering in Nim without GC before I finished getting through the borrow checking chapter in the Rust book.


What's involved in learning to use the GC correctly? I'm very experienced in Rust, and so skeptical when anyone says Rust is easier than something.


It really depends on what you're doing. If you've developing an OS or web browser or game engine you're going to be having to think about memory management very carefully in any event and dealing with Rust's lifetimes is just formalizing the work you'd be doing anyways. But most applications aren't optimized that heavily and as long as you don't have a memory leak or an algorithmic pessimization you don't have to worry about performance in most cases and having a garbage collector is saving you a lot of work.


People do game engines in Nim. ReelValley was even a commercial effort. (This is only to supplement the parent comment, not contradict.)

Your mileage may vary, but several times I've tried some single threaded thing in both Rust, C++ and Nim and the Nim came out faster (e.g. [1] had final Nim version 5.0 ms, C++ 27 ms, Rust 42 ms), not putting much effort into any, and is likely more readable to someone brand new to the language. Writing generic data structures & algos in Nim is also a true breeze/pleasure. Anyway, they are all "fast and maybe-safe by default" and all respond similarly to optimization care. There is no obvious performance disadvantage (and compiling times are much better in Nim, yielding scripting language-like code iteration).

[1] https://news.ycombinator.com/item?id=24817594


Rust algorithm is only one way to do automatic memory management. And regarded as being very restrictive. The scheme Nim implements (ORC), which is innovative as well, is more permissive and unobtrusive. I hope in the next year it becomes the default.


Not writing GUIs in Rust are we?


High level Rust libraries like Yew are pretty straight forward to use.


When the GUI is actually the browser in HTML DOM and JS, with GC.


Fair point, haha.


What do you consider "normal" and "non-normal"?


For me, it's a full stack language, write the frontent with karax https://github.com/pragmagic/karax or react bindings https://github.com/kristianmandrup/react-16.nim and backend in pure nim with any of the available web frameworks (jester/prologue/looper) and orms (ormin/norm) and share code and type declaration between the two.


For a real-life example of this check out NimForum: https://forum.nim-lang.org

The front end is written with Karax (compiled to JS) and the backend with Jester.


How does karax run Nim client side? Cross compile to js or a wasm blob? Or something else entirely?


Nim compiles to js with `nim js source`. I'm not familiar with wasm but it's also possible, know people who have done that.


Nim compiles to js (as well as c and c++)


How much of C and the standard library does it use?

Like, if I wanted to make my own C compiler, how much would I have to implement for it to be usable with Nim-generated code?

Does it use a fairly constrained subset or does it use a lot of C and the standard library?

I imagine the latter but just curious.


Well, it works with TinyCC/tcc where you can get order 200 millisecond compiles. While tcc does do most of c99, I do not think Nim requires anything past c89. libc-wise, it doesn't use even all of standard C. Minimal stdio/string stuff. You can easily access any C libs, though. So, a given program may have more dependency, but that is up to you (or to your Nim package deps).

Full disclosure, not everything works - different backends tend to have slightly different bugs/coverage, but this also applies to c++ and js backends. But I use tcc as my default backend (in my nim.cfg file) every day and only run into problems like a time or two per year.


Doesn't depend much on the standard library -- almost not at all, and usually behind flag (e.g., if you don't -d:useMalloc , nim will not us malloc).

I think it's no longer maintained, but there's a kernel that boots on metal written in Nim. Furthermore, people are running Nim on ESP32, Nintendo Switch, JS (Browser, Node), iOS, Android and more; From that alone its clear that the C library can't be a significant dependency.

(And ... just about any C compiler around, including GCC, LLVM, TCC, MS C, Intel C, Zig C are supported when using C as a backend).


It is just a convenience, Objective-C and C++ also generated code like that on the early days.


I consider Nim to be a compiled, faster Python. Nim is very easy to read and understand, and prototype in, vs. Rust.


Nim looks Pytonish (and has some Python-inspired syntax), but it is very much NOT Python.

People coming from Python that expect a "compiled, faster" Python often find a compiled, faster language but have very weird concepts expecting that language to behave like Python though it isn't.


When I first found Nim I was looking for a faster compiled Python. I've found something that is much better: static types, less of an emphasis on OOP, static dependency-free fast binaries and macros all work together well to make Nim awesome to work with but what makes Python great is retained: speed of development, ergonomic syntax, and a small learning curve.

> very weird concepts

I'm curious, what weird concepts are you referring to?


The Nim forum has recurring questions about deserializing JSON that only make sense if you assume Nim is runtime dynamic like Python.

And many random question start with “Python let’s you..” or “shouldn’t we make this more like Python” to which Araq rather consistently (and rightly) replies “no, because this is not Python”


> The Nim forum has recurring questions about deserializing JSON that only make sense if you assume Nim is runtime dynamic like Python.

Nim is a statically typed Python, and actually the way you can deserialise JSON is very Python-like, so I'm not sure where you got this from. Here is an example:

Python:

    >>> import json
    >>> j = json.loads('{"foo": 42}')
    >>> j["foo"]
    42
Nim:

    import json
    let j = parseJson("{\"foo\": 42}")
    echo(j["foo"]) # 42
https://play.nim-lang.org/#ix=2KpU


But replace the last line with 3+j["foo"] in python (and respectively, echo (3+j["foo"]) in Nim), and the Python prints 45 whereas the Nim compiler greets you with ~40 lines of output asking you what exactly you meant.

Just to clarify: I'm not complaining. I'm happy that the compiler bugs you to do 3+int(j["foo"]) if you're going to treat it as an int. But I don't consider Nim a statically typed Python.

(Also: am a very satisfied owner of a dead-tree version of the Nim book. Thanks! Highly recommended. And dom96 is awesome in general)


Which post, the one forgetting that string literals in JSON are quoted or the other one that paid no attention on the nesting of JSON objects :P


When I started learning Nim, I did not really expect anything, but time and again I caught myself thinking, ‘This is so much like Python!’ Eventually I lost interest because I do not need a faster Python that is not Python, and I didn’t find much else to be enthusiastic about.


I've written a large-ish amount of Nim code on personal projects while using Python day to day at work, and almost every time I'm working with Nim my brain is screaming at me at how unlike Python it is.

Nim took some inspiration from Python's syntax, but the similarity is only skin deep. The construct of the language is very, very different resulting in code that usually looks and is structured differently.

IMO going into Nim thinking it will be like Python but compiled! and faster! with types! is not a good way to approach it. It is an entirely different language altogether.


Actually it feels more like a Python flavoured Object Pascal.


I'm curious - how would you describe the qualitative differences in code structure that results?

Are there ways in which Nim nudges you to structure your code in better ways than you would in Python? Are there footguns?


Yeah, it values composition over inheritance (mentioned in the official tutorials) and discourages you from using methods and other OOP concepts. It's by far a procedural language. Functional style is also not preferred either, imho a good thing, fp does not result in fast code.


I mentioned in what ways it is similar to Python, but of course it is different to it in other ways.


I consider Nim to be a better Go.


Most of them actually, it is only lacking in manpower.

It provides the productivity of having a GC around (no need with coding for borrow checker patterns), you can still go as low level as you want, including writing GC free code, and is very fast compiling code.


This is subjective, but I prefer Nim's python-like scoping syntax; ie no semilonons nor curlybraces. Someone else in this thread posted a comment to the opposite effect! That said, I don't see a compelling class of projects to use it on instead of Rust.

I'll consider Nim next time I'm looking at making a python project. However - most of the times this happens is if I'm making a web backend or doing something numerical, where Python has a library advantage.


Funny how personal preference with regard to some syntax is so polarising - I'm coming from a primarily C# background and while Nim looks interesting, I find the lack of semicolon line endings and the whitespace-based scopes, to be really off-putting!


Syntactic indentation has been very polarizing since at least Python 0.9 (and maybe others) in the late 80s. Like ()s in Nim, Haskell also has a "both brackets or whitespace" kind of vibe.

But, yeah, choice lets different parts of code bases differ. No two ways around that. A ton of people had knee-jerk resistance to Python's lexical style but "got over it" eventually.

There really is a lot more to Nim than just this (its generic/template/macro metaprogramming, user-defined operators, GC options, speed, etc.). Many, many things can be done as libraries that would require direct compiler support in other languages. I would encourage you to give it a try.


> There really is a lot more to Nim than just this

I've actually just been skimming some tutorials and docs, and wow, you're not wrong! I'm impressed - Nim seems to be rammed with features, but also easy to get started with (as long as you ignore some of the more advanced stuff).

I've recently been trying to find time and motivation to start learning Rust, but I have to say that (even with horrible indentation syntax :p ) Nim looks really compelling too...


If a little CLI app to do something useful (instead of say, some shell script/batch file or something) is your entry point then you might try cligen [1]. Everyone is different, but from many and varied reports (e.g. in this very thread [2]), it is hugely more probable that you get up & running with some basic skills in like 30 minutes to 4 hours or so with Nim than you would with Rust. Nim really seems to "scale up gracefully" for most.

[1] https://github.com/c-blake/cligen [2] https://news.ycombinator.com/item?id=25596285


Nim’s available argument parser library needs some more maturity, as compared to Python.

Python has a great argparse library, and it would be good if Nim could emulate that.


Well, cligen is pretty mature/featureful, less work to use and well maintained and is the most common recommendation in Nim. If you happen to like more verbosely specified CLI interfaces like Python's argparse there are at least two pretty close to the Python argparse -- therapist [1] and nim-argparse [2]. There is much more to any programming language than its stdlib. { If you find these insufficiently "drop-in compatible", well, you can write your own port of argparse.py that is closer. :-) That is probably a good exercise. }

[1] https://maxgrenderjones.bitbucket.io/therapist/latest/therap...

[2] https://www.iffycan.com/nim-argparse/argparse.html


I did entertain that idea. But it would’ve detracted my efforts from my actual goal.

therapist looks interesting. I’ll take a look at this. Thanks.


Nim compiles way faster, which can be a huge boost to productivity. It's also a lot easier to metaprogram in Nim




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: