27 ms·
A comparison of Rust’s borrow checker to the one in C#
- bob1029 2y ago> Maybe I’m bad at searching for these things, but these changes to C# seem to have gone completely under the radar in places where you read about memory safety and performance. Maybe it’s just because the language additions have happened super slowly, or maybe the C# and Rust communities have so little overlap that there aren’t enough people who program in both languages to notice the similarities. If you are looking at this through the lens of HN, I think much of this can be attributed to a certain ideological cargo cult that actively seeks to banish any positive sentiment around effective tools. You see this exact same thing with SQL providers, web frameworks, etc. If the tool is useful but doesn't have some ultra-progressive ecosystem around it (i.e., costs money or was invented before the average HN user's DOB), you can make a winning bet that talking about it will result in negative karma outcomes. Everyone working in enterprise software development has known about the power of this language for well over a decade. But, you won't find a single YC startup that would admit to using it.
- deleted 2y ago[deleted]
- zdragnar 2y agoWell, common lisp and some schemes and prolog tend to get a good deal of praise here, even if their commercial utilization is lower. OCaml, F# and Clojure tend to get a good deal of favorable comments as well. I suspect it is less about cargo culting, and more about two separate things: First, the tooling for C# and really anything dotnet has been awful on any OS other than Windows until fairly recently. Windows is (to be blunt) a very unpopular OS in every development community that isn't dotnet. Second, anthing enterprise is worth taking with a skeptical grain of salt; "enterprise" typically gets chosen for commercial support contracts, vendor lock-in, or astronaut architects over-engineering everything to fit best practices from 20 years ago. Saying big businesses run on it is a virtue is akin to saying that Oracle software is amazing or that WordPress engineering is amazing because so many websites run on it. Popularity and quality are entirely orthogonal. I suppose there is probably another reason, which is the cluster fuck that has been the naming and churn of dot net versions for several years. ASP.NET, then core, then the core suffix got dropped at version 5, even though not everything was cross platform... So much pointless confusion.
- devjab 2y ago> Everyone working in enterprise software development has known about the power of this language for well over a decade. I think it depends on location. In my part of the world .Net is something which lives in middle sized often stagnating companies. Enterprise around here is married to the JVM and they even tend to use more Typescript on the backend than C#. I’m not going to defend the merits of that in any way, that is just the way of things. There being said I do get the impression that HN does know that Rust isn’t seeing much adoption as a general purpose language. So I wouldn’t count C# out here considering how excellent it has become since the transition into Core as the main .Net. I say this a an absolute C# hater by the way, I spent a decade with it and I never want to work with it again. (After decades of SWE I have fun with Python, C/Zig, JS/TS, and, no other language.)
- DeathArrow 2y ago> Enterprise around here is married to the JVM and they even tend to use more Typescript on the backend than C#. I’m not going to defend the merits of that in any way, that is just the way of things. Many developers already know Java, so it's easier to hire Java developers. >There being said I do get the impression that HN does know that Rust isn’t seeing much adoption as a general purpose language. So I wouldn’t count C# out here considering how excellent it has become since the transition into Core as the main .Net. I say this a an absolute C# hater by the way, I spent a decade with it and I never want to work with it again. (After decades of SWE I have fun with Python, C/Zig, JS/TS, and, no other language.) I didn't like the old C# and .NET. However, the new one is wonderful and I quite enjoy using it. More than Java or Go. On par with Python, but I wouldn't use Python for now for large web backend applications. I tried Rust, bur for some reason I can't grow to like it. I'd prefer using C or Zig and even a sane subset of C++ (if such thing even exists).
- devjab 2y agoI don’t like C# because I don’t like the “magic” which is also what makes it special. In that regard I actually think highly of Go’s more simplistic approach to everything, from explicit error handling to the flat “class hierarchy”. Go isn’t as good as C# for a lot of things and there are no technical reasons for my C# hatred. Well I guess you could argue that having to fight the “magic” when you run into things it can’t handle as technical but for 99% of the things this isn’t an issue. Python is a horrible language, but it’s also the language I actually get things build in. I do think it’s a little underrated for large web apps since Django is a true work horse, but it takes discipline. C is for performance, embedded and Python/Typescript libraries and Zig is basically just better C because of the interoperability. Typescript is similar to Python for me, I probably wouldn’t use it if it wasn’t adopted everywhere, but I do like working with it. We’ve done some Rust pocs but it never really got much traction and nobody really likes it. + I don’t think I’ve ever seen a single Rust job in my area of the world. C/C++ places aren’t adopting it, they are choosing Zig. That is if they’re going away from C/C++ at all.
- WD-42 2y agoI think it has more to do with c# being a Windows only programming language for the majority of its life. And guess what, a lot of people don’t like Windows. And don’t bring up mono, etc. it was a dumpster fire then and it’s only recently gotten better. It tough for any tech to shed a very long negative legacy.
- Kipters 2y ago.NET Core 1.0 was released cross-platform 8 years ago though, there's a ton of new devs for who it has always been cross-platform
- WD-42 2y agoAnd Rust 1.0 (which this article seems to be comparing against) came out 9 years ago. These things take time.
- palmfacehn 2y agoReading this thread is the first I'm learning of this. Even with the enthusiasm expressed here, I'm still suspicious that there will be incompatibilities. Microsoft has a history of doing things a certain way.
- sfn42 2y agoWe use .NET for pretty much everything that doesn't run in a browser, our apps run in Linux containers and devs use windows/Linux/Mac with no issues. GUI libraries might have some potential for improvement but I would reach for C# for any task that didnt strictly require a different language.
- Kipters 2y agoThat's your bias and not the language fault, everything works pretty much the same across every OS, I haven't developed non-UI C# apps on Windows since 2018 (because of course you need Windows to build WinUI and WPF apps, but you have options on macOS and Linux too)
- DeathArrow 2y agoI don't get why you are downvoted. It's true that some languages, frameworks, operating systems are more popular on HN that others. Reasons for this might be complex and we might enter into very hard and complicated sociological arguments if we try to discuss them. >Everyone working in enterprise software development has known about the power of this language for well over a decade. What is an enterprise? Is Google not an enterprise? Is Apple not an enterprise? Is Facebook not an enterprise? What about Netflix, Uber and any other big tech company? Weren't all enterprises start-ups at the beginning? Does enterprise mean boring old company established long before the invention of Internet, which does old boring stuff, employs old boring people and use old boring languages? I imagine a grandpa with a long white beard staring at some CRTs with Cobol code and SAP Hana.
- wongarsu 2y agoIn this context I'd interpret enterprise to mean any company with over 1000 employees that is not what Silicon Valley calls a tech company. So no Apple, Google or Uber, but the notable players of basically every other industry, from A for accommodation or accounting to W for wood paneling. But I wouldn't say their choice of C# is due to them being old and boring. If it was that, they'd use Java (as many do). In my eyes choosing C# signals to me that you do want good technology (again, you could have gone with Java), but want that technology to be predictable and boring. A decent rate of improvement with minimal disruption, and the ability to solve a lot of issues with money instead of hiring (lots of professionally maintained paid libraries in the ecosystem).
- Ygg2 2y ago> ...actively seeks to banish any positive sentiment around effective tools Effective at what? Want GC lang with lots of libraries? Use Java. Want GC free lang with safety? Use Rust. Otherwise just use C. Or C++. For me C# lies in this awkward spot. Because of past decisions it will never have quite the ecosystem of Java. And because GC -free and GC libraries mix as well as water and oil, you get somewhat of a library ecosystem bifurcation. Granted GC-less libraries are almost non-existent.
- DeathArrow 2y agoI worked in both C# and Java. And other languages. Resuming C# and Java to "GC languages with lots of libraries" doesn't accurately depict neither C#, nor Java. Since we discuss C# here, it is a good jack of all trades language where you can do almost anything, with decent performance, low boilerplate. It's easy to read, easy to learn and you have libraries for everything you need, excellent documentation and plenty of tutorials and examples. A great thing is that for every task and domain there is a good library or framework that most developers use, so you don't have to ask yourself what to use and how and you find a lot of documentation, tutorials and help for everything. Java it's a bit more boiler plate-y, had a bit less features and ease of use and had many libraries and frameworks that did the same thing. Had Java been better, Kotlin wouldn't need to be invented. >Want GC lang with lots of libraries? Use Java. Want a fast to develop and easy to use language? Just use C#. >Want GC free lang with safety? Use Rust. Want a language which you can use for almost eveything? Web front-end, web backend, services, microcontrollers, games, desktop and mobile? Use C#. >Otherwise just use C. Or C++. Or whatever works for you. Whatever you like, find fun and makes you a productive and happy developer. There is nothing wrong in using C or C++. Or Python. Or Haskell.
- Ygg2 2y ago> Since we discuss C# here, it is a good jack of all trades language where you can do almost anything, with decent performance, low boilerplate. That's basically modern-day Java, with Lombok and other tidbits. Furthermore, if I recall correctly, Java has better performance on web benchmarks than C#. > Had Java been better, Kotlin wouldn't need to be invented. Kotlin was invented to make a sugary version of Java, and thus drive more JetBrains sales. It got popular because Oracle got litigious. As someone who's been on the Java train for almost two decades, what usually happens, if any JVM Lang becomes too popular, Java has the tendency to reintegrate its features into itself. > Whatever you like, find fun and makes you a productive and happy developer. There is nothing wrong in using C or C++. Or Python. Or Haskell. Sure, assuming it fits the domain. Like, don't use Python for kernel dev or Java for some obscure ML/AI when you could use Python.
- DeathArrow 2y ago> Everyone working in enterprise software development has known about the power of this language for well over a decade. But, you won't find a single YC startup that would admit to using it. Not sure about that. Maybe there are? If you do web or mobile apps, C# would be an excellent choice. Go would be also an excellent choice for web. For AI I wouldn't use C#. Even though it has excellent ML libraries, most research and popular stuff is done using Python and pytorch, so that's what I would chose. For very low level, I'd take C or Zig. But I don't know many startups who are into very low level stuff.
- jeroenhd 2y agoC# is an incredible language with a past haunted by Microsoft only making it useful on Windows and expensive licenses for really good editors. It's come a long way, but I don't blame people for thinking of it as "Microsoft Java". My only issue with many of the improvements in C# is that all of them are optional for backwards compatibility reasons. People who don't know or don't care about new language features can still write C# like it's 2004 and all of the advantages of trying to modernize go out of the window. That means that developers often don't see the need to learn any of the new features, which makes it hard for projects to take advantage of the language improvements.
- alkonaut 2y agoHard agree on the backwards compatibility. It appears to be some law of nature that "our next compiler must compile 20 year old code". Instead of new platform libs and compilers simply defaulting to some reasonable cutoff date and saying "You need to install an ancient compiler to build this". There is nothing that prevents me from building my old project with an older set of tools. If I want to make use of newer features then I'm happy to continuously update my source code.
- Clubber 2y ago>It appears to be some law of nature that "our next compiler must compile 20 year old code". Some examples of companies/products not implementing backwards compatibility are Delphi and Angular. Both are effectively dead. .NET Core wasn't backwards compatible with .NET Framework, but MS created .NET Standard to bridge that gap. .NET Standard allows people to write code in .NET core and will run in .NET Framework. It's not perfect, but apparently it was good enough. Companies usually won't knowingly adopt a technology that will be obsoleted in the future and require a complete rewrite. That's a disaster.
- alkonaut 2y agoBut that's .NET, not C#. Language and platforms are different. Libraries must be compatible (because you don't know if your library will be consumed in a newer app). But the compiler only consumes syntax (C#11, C#12 C#13 and so on) so I don't see why the compiler that eats C#13 necessarily must swallow C#5 without modification
- johnisgood 2y agoYeah, or you think Ada / SPARK ever comes up when people cry for memory safety? It has existed in Ada / SPARK for ages, but nah...
- failbuffer 2y agoAlternatively (or at least additively), most C# developers don't really need all the new ref/Span features. They're writing line-of-business apps and garbage collection is a fact of life, not some burden to be avoided. Microsoft probably added these features to push the language into new niches (like improving the story around Unity and going after Arduino/IoT). But it's of little practical appeal to their established base.
- Dykam 2y agoAs far as I'm aware, it's the development of Kestrel which pushed the introduction of ref/Span etc. Due to it Kestrel has seen quite a large speedup, it being one of the fastest HTTP servers nowadays. ref/Span allowed them to make the core almost allocation free, together with using vectorized operations (SIMD ) for parsing the request.
- neonsunset 2y agoWhat a great article, thank you for sharing it!
- zigzag312 2y agoI always felt like these features are adding a new programming paradigm to C# that allows you to bypass GC in safe code. I wish more people would talk about it. Thank you for such an interesting article!
- pjmlp 2y agoMany of these features exist since .NET 1.0, given its scope of languages to support, including C++. So even those that weren't initially exposed in unsafe mode, were available at the MSIL level and could be generated via helper methods making use of "System.Reflection.Emit". Naturally having them as C# language features is more ergonomic and safer than a misuse of MSIL opcodes.
- zigzag312 2y ago"System.Reflection.Emit" is not compatible with NativeAOT. Using C/C++/Rust to do the same task is probably more productive than emitting MSIL opcodes, so that solution wasn't really that practical. But with these new features being more ergonomic and practical, it becomes cost effective to just do it in C# instead of introducing another language.
- deleted 2y ago[deleted]
- pjmlp 2y agoYeah, but nothing of that is the point being discussed, with Native AOT still not available in GUI workloads. Also P/Invoke and CCW/RCW do have costs cross the runtime layer, even if minor when compared with other languages.
- zigzag312 2y agoI'm not sure I follow. Where are GUI workloads being discussed in the article? If anything, article doesn't talk about MSIL or CLR, but C# language features. CLR is not the only target C# supports. NativeAOT is supported in Avalonia (cross-platform UI framework), Razor Slices (dynamically render HTML from Minimal APIs) and I think there is also some support for AOT in MonoGame & FNA (game dev frameworks). However, it's still early and a lot of the ecosystem doesn't support NativeAOT.
- stonethrowaway 2y agoC# is Pragmatic [0]. [0] https://news.ycombinator.com/item?id=41761346 https://news.ycombinator.com/item?id=41761346
- lowbloodsugar 2y ago>This restriction is central to Rust’s safety guarantees, but C# doesn’t need it. The reason is that Rust has to account for the possibility that a reference may be invalidated at any time. That’s not why though. There’s lots of reasons for Rusts safety model, such as allowing for vastly faster code because aliasing can’t happen unless both references are read only, in which case it doesn’t matter. There is lot to Rusts borrow rules that this article misses. It’s like the article earlier today that was, essentially, “I don’t understand Rust and it would be better if it was Haskell”.
- fulafel 2y agoIs there some benchmarking work that has quantified this speedup from aliasing guarantees or is this more of a sufficiently smart compiler[1] thing? [1] https://kidneybone.com/c2/wiki/SufficientlySmartCompiler https://kidneybone.com/c2/wiki/SufficientlySmartCompiler
- DonaldPShimoda 2y agoThe Sufficiently Smart Compiler is a hypothetical argument used in advocating for a programming language whose naive implementations might tend towards inefficient designs, whereas the aliasing argument is not itself hypothetical but it may not be backed by data. That's a different thing altogether. Whether the aliasing argument holds water does not affect whether it was used as justification for Rust's design.
- vlovich123 2y agoOf course: https://github.com/rust-lang/rust/issues/54878#issuecomment-767151730 https://github.com/rust-lang/rust/issues/54878#issuecomment-... TLDR: 0-5% faster with noalias optimizations on. You can always try running some benchmarks by building code with -Zmutable-noalias=no.
- fulafel 2y agoThanks. If anyone has a link to results handy I'd be intersted. In particular a lot changes can be said to be 0-5% where the average is very close to 0...
- DonaldPShimoda 2y ago> Instead of throwing an exception, we’ve decided that this function should always return something, even if it’s not in the haystack The right move at this point would be to use an optional type, surely...
- vlovich123 2y ago> This restriction is central to Rust’s safety guarantees, but C# doesn’t need it. The reason is that Rust has to account for the possibility that a reference may be invalidated at any time. Is this right? I thought Rust's reason for XOR is deeper & is how it also guarantees memory safety for multi-threaded code too (& not just for reference lifetimes).
- lionkor 2y agoThat's how I understood it, too
- Animats 2y agoSo what are the C# compiler lifetime error messages like? It if guesses about lifetimes, the messages have to be good.
- lionkor 2y agoThe article has some examples
- leosarev 2y ago> Maybe I’m bad at searching for these things, but these changes to C# seem to have gone completely under the radar in places where you read about memory safety and performance. The reason is this changes are not aimed on average Joe developer writing C# microservices. This changes and whole Span/ref dialect of C# are aimed on Dr. Smartass developer writing C# high performance libraries. It's advance-level feature.
- yread 2y agoThe article that introduced them talks about mainstay and is certainly not trying to hide their impact https://learn.microsoft.com/en-us/archive/msdn-magazine/2018/january/csharp-all-about-span-exploring-a-new-net-mainstay https://learn.microsoft.com/en-us/archive/msdn-magazine/2018...
- DeathArrow 2y agoI use low level C# constructs, mostly for fun. At current job we write backend microservices and our business domain doesn't need too much low level stuff. But before span and friends you could always use pointers. Spans just make things friendlier. And C# also has built-in SIMD libraries if you need to do some high performance arithmetic stuff.
- bob1029 2y agoI don't think Span<T> and ref are particularly sophisticated concepts. Span makes working with large buffers easier for Joe developer, if he could be bothered to spend 20 seconds looking at the examples in the documentation.
- EVa5I7bHFq9mnYK 2y agoAll this "advance" stuff does is work around the too clever memory model and allow to simply allocate data on stack, something invented ~60 years ago.
- WorldMaker 2y agoC# always supported stack allocations and always supported things like stack-based pointer operations. It just tagged a lot of it as "Unsafe" and/or required the `unsafe` language keyword (and concomitant security escalation in the old Framework security model where assemblies that used `unsafe` code needed additional code certificates to be installed into places like the GAC). The "advanced" stuff is very much about bringing Rust-like lifetimes to the language and moving the powers and capabilities outside of the `unsafe` keyword world, by making it much less unsafe in similar ways to how Rust does lifetime/borrow-checking but converted to C#/CLR's classic type system. It's adding the "too clever" memory model of Rust to the much simpler memory model of a GC. (GCs are a very simple memory model invented ~70 years ago.)
- DeathArrow 2y ago>How is it possible that I can write efficient and provably-safe code in C# without a degree in type theory? Because Anders Hejlsberg is one of the greatest language architects and the C# team are continuing that tradition. The only grudge I have against them is they promised us discriminated unions since forever and they are still discussing how to implement it. I think that is the greatest feature C# is missing. For the rest C# is mostly perfect. It has a good blend of functional and OOP, you can do both low level and high level code. You can target both the VM or the bare hardware. You can write all types of code beside system programming (due to the garbage collector). But you can do web backend, web front-end, services, desktop, mobile apps, microcontroller stuff, games and all else. It has very good libraries and frameworks for whatever you need. The experience with Visual Studio is stellar. And the community is great. And for most domains there is generally only one library or framework everybody uses so you not only don't have to ask what to use for a new feature or project, but you also find very good examples and help if you need. It feels like a better, more strait trough version of Java, less verbose and less boiler plate-y. So that's why .NET didn't need its own Kotlin. Sure, it can't meet the speed of Rust or C# for some tasks because of the garbage collector. But provided you AOT compule, disable the garbage collector and do manual memory management, it should.
- jabwd 2y agoExcept that the GC makes it exactly not viable for games and its one of the biggest problems Unity devs run into. I agree it's a great language, but its not a do it all.
- lmm 2y agoMany of the top games in recent years have used it, so you've got a funny definition of "not viable".
- johnisgood 2y agoOr roll their own, so they used GC in one way or another.
- 2y ago
- yeputons 2y ago>How is it possible that I can write efficient and provably-safe code in C# without a degree in type theory? Because of two things mentioned in the article just below. > Here we see C#’s first trade-off: lifetimes are less explicit, but also less powerful. If C# is less powerful, it does not need powerful syntax. One does not need explicit lifetimes in Rust for a long time either, deduction work just fine. > The escape hatch: garbage collection If C# is ok with not tracking _all_ lifetimes _exactly_, it does not need powerful syntax. Not an option in Rust, by design. Basically, not all code is possible to write, and not all code is as efficient.
- daxfohl 2y agoBoth have "unsafe" escape hatches, so all code is possible to write efficiently. Just some cases are harder to prove correct in the type systems of each.
- sirwhinesalot 2y agoThe sort of "borrow checking" C# does is also similar to what the lifetime profile for C++ tries to do to catch bugs (but that's sadly a bit of a shitshow, existing C++ code is too much of a mess). A related idea are the concept of second class references, as exist in Hylo. There the "ref" is not part of the type, but the way they work is very similar. Lifetimes give you a lot of power but, IMO, I think languages that do this should choose between either being fully explicit about them, or going "second class" like C# and Hylo and avoiding lifetime annotations entirely. Eliding them like Rust does can be convenient for experts but is actually a nightmare for newbies. For an example of a language that does explicit lifetimes without becoming unbearable, check out Austral. Instead of C#'s scope ref solution to having a function accept and return multiple references, another option (in an imaginary language) would be to explicitly refer to the relevant parameters: ref(b) double whatever(ref Point a, ref Point b) { return b.x; }
- pjmlp 2y agoIn theory, unfortunately VC++ and clang implementations since 2015 still leave too much off the table for us to fully rely on their lifetime static analysis.
- nickitolas 2y agoYou're correct that as far as I understand it the analysis propsoed by the C++ Lifetime Safety Profile is similar in many ways, however I think there's a few important distinctions with these C# features that are not directly related to the analysis: The C++ safety profilers are trying to be backwards compatible with as much C++ code as possible. Whereas my understanding is most of what's talked about in this post is sort of a clean break from idiomatic C#, and is not changing the semantics or adding new warnings to any pre-existing code. Another difference is that C++ obviously does not have a built in runtime GC, so the situations mentioned in this post that get "fixed" by GC heap allocation would remain an issue.
- sirwhinesalot 2y agoYes, I only meant that the way they work (meaning how the "lifetimes" are tracked) is very similar. C++ has to be "best effort" because it tries to bolt these semantics onto the pre-existing reference types, which were never required to adhere to them. It can catch some obvious bugs but most of the time you'll get a pile of false positives and negatives.
- PoignardAzur 2y agoCool article! Quick nitpick: the find example could return a reference to a static variable, and thus avoid both the heavy syntax and the leaked allocation: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=90f8ac4e1b30141f3f0992c404cba473 https://play.rust-lang.org/?version=stable&mode=debug&editio...
- Arnavion 2y agoIt doesn't even need to be a `static`. It can be `const` or just inlined `&0` because borrows of consts get promoted to `'static`
- raverbashing 2y ago> How is it possible that I can write efficient and provably-safe code in C# without a degree in type theory? Excellent question And I feel that Rust, by making it explicit, makes it harder and unergonomic on the developer
- Decabytes 2y agoMy biggest issue with C# is that it doesn't have a good cross platform GUI. Maui dev is too slow and lacks a lot of the features a lot of people want, and Avalonia still uses the hybrid axml approach that just feels bad. I wish C# had a Flutter like library that utilized C#'s Hot Reload features
- zigzag312 2y agoI agree. Avalonia tries too much to be like WPF, but in my opinion, WPF was two steps forward and one step back (mainly due to XAML).
- neonsunset 2y agoYou have Avalonia, Uno Platform and, yes, MAUI. Most cross-platform GUI frameworks are flawed regardless of the language. The ones .NET has are decent, with various ways to approach the UI wiring - you have both XAML and declarative SwiftUI-style (and with MVU pattern too) options. Avalonia even has F# support through FuncUI. There are also plenty of bindings for SDL2, there's GTK# successor Gir.Core. I wish the comments focused more on the subject of the article which is interesting and under-discussed.
- fire_lake 2y agoMAUI is the official one but Linux support AFAICT? Such a shame!
- kkukshtel 2y agoUsing something like Photino (https://www.tryphotino.io https://www.tryphotino.io) with Blazor can start to feel like an actual good C# cross plat GUI solution but even as a C# truther I agree with you. I think you'll start seeing a lot more "cross platform C# frameworks" when PanGUI drops: https://pangui.io https://pangui.io It's a native layout/gui util by the devs of the mega-popular Odin extension in Unity, and the idea is to directly solve "good native c# gui lib" with the implementation just being a single shader and an API that is more like DearIMGUI. I'm also planning on using it my own small 2D C# engine when it's available: https://github.com/zinc-framework https://github.com/zinc-framework I already do iterative hot reload GUI with DearImGUI in that engine so PanGUI will work in the same way.
- not2b 2y agoFor the first example, for C or C++ code gcc will catch the dangling reference/pointer and warn about it, and since my group normally turns on -Wall -Werror, it's an error. However, the analysis is local and not as powerful as Rust's borrow checker. Try int* bug() { int longlived = 12; int* plonglived = &longlived; { int shortlived = 13; plonglived = &shortlived; } return plonglived; } With gcc -Wall -Werror
- akira2501 2y ago> The defaults can also be unintuitive: say we wanted to write a method on a struct which returns a reference to one of the struct’s members. Why would you do that? > n fact, this is so common that Rust doesn’t require you to write the lifetimes explicitly This is an actual _pattern_? Yikes^2.
- 0x457 2y ago> Why would you do that? a getter? > This is an actual _pattern_? Yikes^2. wat.
- akira2501 2y ago> a getter? Getters return values. This returns a pointer. So it's an accessor. With unchecked semantics. It's bizzare to me that anyone would use this technique. It's all downside with no upside. > wat. I'm expressing surprise that anyone would do this. I'm sure you were capable of understanding that.
- 0x457 2y ago> Getters return values. This returns a pointer. So it's an accessor. With unchecked semantics. It's bizzare to me that anyone would use this technique. It's all downside with no upside. When I use getter, I want to see the value of a field. I don't want an owned copy of said value, I just want to look at it, so returning reference makes _a lot more_ sense than returning a copy. In example it uses `i32`, but that's just for readability. > I'm expressing surprise that anyone would do this. I'm sure you were capable of understanding that. Yes, and I'm expressing surprised that you think it's bad. I'm not even sure what is bad? Lifetime elision that is well documented and works in a non-ambiguous manner? Using references instead of values? Do we need to memcpy overything now to please you?
- akira2501 2y ago> I want to see the value of a field. I don't want an owned copy of said value, I just want to look at it, so returning reference makes _a lot more_ sense than returning a copy. You can look at it with an owned copy. What is the issue? Is premature optimization the default mode in writing Rust? You don't see the issues with this? > I'm expressing surprised that you think it's bad You're surprised that someone simply has a different opinion? Your reaction failed to convey that.
- lowleveldesign 2y agoI feel that nowadays Rust is the language to go when you are doing system programming, but C# is not a bad choice either. With .NET 9 being released in a few weeks we will get NativeAOT (compilation to a native single binary) for x86 (x64 and ARM64 are already available). At work, I'm writing patches for legacy apps and needed to use C++ for most of my tasks. Nowadays, I'm doing more and more stuff in C# and enjoying it. For WinAPI there is a fantastic cswin32 [1] project that generates FFIs signatures on the fly. And it's fairly simple to extend it for other Windows libraries (I did it for detours [2], for example). And using pointers or working with native memory blocks is straightforward and intuitive for people with C/C++ background. [1] https://github.com/microsoft/CsWin32 https://github.com/microsoft/CsWin32 [2] https://lowleveldesign.wordpress.com/2024/07/11/implementing-a-native-function-detour-in-csharp/ https://lowleveldesign.wordpress.com/2024/07/11/implementing...
- starquake 2y agoAlthough NativeAOT sounds cool and it's better than nothing: I don't like that it comes with a bunch of limitations[1]. I would have loved this if you could just use it without any changes, but I'm very worried that at some point I used something that prevents me from getting it to work and I have to figure out which limitation I just walked into. Correct me if I'm wrong. [1] https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?tabs=windows%2Cnet8#limitations-of-native-aot-deployment https://learn.microsoft.com/en-us/dotnet/core/deploying/nati...
- Kwpolska 2y agoThose limitations are often obvious. With AOT, you don't have the VM around, you can't load new bytecode or introspect the objects. I would focus on writing working code, and try to go AOT close to the end. If it fails and it's not fixable, tough luck, but it works on the standard runtime.
- taberiand 2y agoThat's interesting - I would have thought targeting aot at the outset and then switching away only when the design became incompatible would be more effective, only because by going for aot at the end I'd probably have introduced some code or dependency that isn't aot compatible and yet too much work to replace
- two_handfuls 2y agoThings could have gone so much differently if they had committed early on to being cross-platform. Instead, its growth was stunted and many people avoid it even though it is an excellent language.