12 ms·
An unordered list of things I miss in Go
- seabrookmx 2y agoC# also solved the nullability problem after the fact. It integrates well with the "?." operator also found in Typescript.
- dexwiz 2y agoOptional chaining is now in vanilla JS. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- KronisLV 2y agoThis is really pleasant, when combined with the nullish coalescing operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... const isStatusValid = myStore.someObject?.isStatusValid ?? false; (e.g. if some data is not initialized along the way, or you put in some new object which just isn't meant to have that field but some related logic needs to check for it)
- neonsunset 2y agoYup, it is Kotlin-style nullability analysis that is a default everywhere now. The last place that does not have ideal behavior is System.Text.Json, but that is fixable with a flag, maybe two, and there are edge cases where static analysis can't see through some expressions and assumes null so you have to specify it isn't with '!'. Nonetheless, works great with '??', '??=' expressions, required fields/props and pattern matching. From practical standpoint, a project with Nullable: enable, WarningsAsErrors: nullable has almost never have to think about unexpected nulls again - a solved problem.
- devjab 2y agoHaving nullability has its own set of issues. I prefer explicit error handling to null checks. That being said, I don’t think there is really that much of a difference in that you might use Interface as a JS Any sort of thing in Go (it’s obviously difference), and where you would deal with nil pointers is often where you would perform a null check anyway. I prefer the go style of doing a check every time rather than some of the time with the risk of missing a time. Or on the flip-side simply defining your own default. I know that a lot of people like how C# is becoming more and more reliant on the compiler to handle type checks, but it also opens up the risk of more developer mistakes. It’s mostly down to opinion and preference. So I don’t think you can really call it a “problem” as such. Having nullability will be a feature to some, and not having it will be a feature to others. I think both decisions were right for their respective languages. C# needs it for its close integration with mssql and its exception handling. Go doesn’t want it because it favours simplicity in types and direct error handling.
- masklinn 2y ago> Having nullability has its own set of issues. I prefer explicit error handling to null checks. Nullability does not preclude explicit checks. In fact it requires them. Which Go currently does not: you can dereference any pointer or use any interface and it will blow in your face if either is nil. > C# is becoming more and more reliant on the compiler to handle type checks, but it also opens up the risk of more developer mistakes. That literally makes no sense. The entire point of moving checks to the compiler is that it catches developer errors upstream and prevents them. > C# needs it for its close integration with mssql and its exception handling. That's a nonsensical just-so story. Go on, explain how Haskell or Swift or Zig have explicit nullability for their close integration with mssql and exception handling (and while at it, do explain the relationship between exception handling and nullability)
- bediger4000 2y agoI've seen the python ordered dict thing bite ex-python programmers over and over, in two different ways. First, assuming that the keys iterate in the order they're inserted, the cliche problem. Second, marshalling JSON and unconsciously relying on the order in the JSON as hidden semantics. This makes it hard to understand the JSON as a human, as well as making what ought to be a portable format with other languages hard to reuse. I've decided that Python is in the wrong here, not technically, but rather for encouraging humans to assume too much.
- zarzavat 2y agoAs the article says, reproducibility is important. If I have a bug on one run, I want to get that bug again on the second run. I want to be able to run the program again and again and have the same breakpoints hit in the same order with the same variables. If I run tests, I want them to give the same results each time. Randomness is bugs. Adding randomness to a language is adding bugs.
- dwattttt 2y agoYou can't avoid randomness and entropy, it's just something that's needed in too many places. For test repeatability though, whatever seeds a test run uses should be saved in order to repeat that test exactly. Best of both worlds: you get to cover weird bugs that only show up when stuff is in a certain order, and you can repeat the tests exactly.
- kokada 2y ago> First, assuming that the keys iterate in the order they're inserted, the cliche problem. Author here. I never assume that hash maps can be iterated in the same order as the insertion in any language, however the fact that in Go each iteration results in a different ordering is surprising.
- bediger4000 2y agoGood practice. My experience says that Python programmers consciously or unconsciously make that assumption often, which is bad practice.
- cempaka 2y ago> While I understand the reason for this (i.e.: to avoid developers relying in a specific iteration order), I still find it weird, and I think this is something unique for Go. Haha well, fun fact, Java did this as well after a bunch of code was broken by a JDK upgrade which changed HashMap iteration order that programmers had been relying upon. Java does at least have ordered maps in the standard lib though. IMO it is a questionable decision to spend CPU resources on randomization in order to mollycoddle programmers with a flawed understanding of an API like this, but then again I'm not the one who gets the backlash when their stuff breaks. Also, on the subject of nullability, while JSR305 may be considered dead, there's still pretty active work on the Java nullability question both from the angle of tooling (https://www.infoq.com/news/2024/08/jspecify-java-nullability/ https://www.infoq.com/news/2024/08/jspecify-java-nullability...) and language design (https://openjdk.org/jeps/8316779 https://openjdk.org/jeps/8316779).
- jillesvangurp 2y agoIt's one of the things I like in Kotlin: it defaults to using ordered maps. It also has default arguments in functions, lambda functions, and of course nullable types.
- kevindamm 2y agoI was about to comment the same. Also happened in absl (Google's alternative to the STL template library for C++ which started its life as GTL) -- when changing the default hash function for unordered maps it led to breaking changes in both test and production code that had depended on it. OrderedDict types are nice sometimes but shouldn't be the default behavior, IMO. There are good reasons for the second point (about default/named parameters) -- any calling code is making some assumptions based on that default value so there's a risk it can't be changed or added to. If you really want a default value, make a wrapper function for it. In the example it would be a simple matter of defining ReplaceAll with three arguments that always passes -1 to Replace(...)
- Groxx 2y agoBecause it came up recently for me (triggered a starvation bug), a caution for people expecting Go to randomize everything like this: Blocked channel reads and writes are unblocked in FIFO order, not random. Mutexes are similar (afaict not quite identical, but the intent is the same). Go randomizes a lot and I am thrilled they do that, and I knew about mutexes already, but the chan part was a surprise to me. It's reasonable and matches mutexes, so that's probably for the better, but still a bit oof.
- pcwelder 2y agoI am a Python programmer with a bit of Golang experience. If it were upto me I'd absolutely do away with default function arguments in Python. It is one of the rules now I live by. I don't have to worry about leaving an argument during calling anymore. I think it fits well with the pythonic mantra of explicit is better than implicit.
- margalabargala 2y agoDefault arguments being hidden/unclear/wrong/hard to find/undocumented is by far the #1 source of bugs I encounter in Python programs. It's not even close. Probably around 70%.
- lpribis 2y agoEven worse when you see function X takes some parameters and then passes *args and **kwargs to a client function. Makes the available (or required) parameters very difficult to track down.
- richrichie 2y agoI agree. But there are places it is clearly useful. pandas.read_csv is a good example.
- BoingBoomTschak 2y agoThe reason for randomized hash is most probably to mitigate DOS attacks based on users knowing which hash function is used (Go is open source, after all) and finding a way to fill a map - any map - with untouched tokens.
- materielle 2y agoThat’s definitely part of it. The other half is hyrum’s law. There’s a lot of situations in reasonable unordered map implementations where the elements, by chance, do happen to be ordered. Just due to arbitrary implementation decisions. But the Go spec says that maps are unordered, and library writers want to reserve the right to change the implementation in the future. So always ransoming the dict prevents code from accidentally depending on some specific map implementation detail.
- jhgg 2y agohttps://go.dev/doc/go1#iteration https://go.dev/doc/go1#iteration > The old language specification did not define the order of iteration for maps, and in practice it differed across hardware platforms. This caused tests that iterated over maps to be fragile and non-portable, with the unpleasant property that a test might always pass on one machine but break on another. > In Go 1, the order in which elements are visited when iterating over a map using a for range statement is defined to be unpredictable, even if the same loop is run multiple times with the same map. Code should not assume that the elements are visited in any particular order. > This change means that code that depends on iteration order is very likely to break early and be fixed long before it becomes a problem. Just as important, it allows the map implementation to ensure better map balancing even when programs are using range loops to select an element from a mapl.
- materielle 2y agoInteresting, I agree with the the main idea: in general I find Go a productive language, but there’s a few rough edges. The specific examples don’t ring true to me though. Instead of named arguments, use the functional optional pattern. An ordered map can be implemented as a slice with a get function. If you want to stamp out some code duplication, Go has generics and iterators these days. What I really miss are enums. Specifically, the ability to map two value sets to each other and get a compile time error if the mapping becomes stale due to a new value. And other assorted stuff. Like better nil handling, the weird time and http client libraries, nil interfaces and slices, and so on.
- RSHEPP 2y agoOh interested in the issues with http clients you have? I think they are great to use for being right in the standard library. Only complaint I have is defaults for timeouts and such, but you make that mistake once and don't forget.
- materielle 2y agohttps://blog.carlana.net/post/2021/requests-golang-http-client/ https://blog.carlana.net/post/2021/requests-golang-http-clie... I don’t think that article discusses the timeout issue. So all the issues mentioned in that article, plus the timeout issue. The end result is you have to explain to every Go developer that they can’t use the http client as-is. Start searching for http client usages in GitHub. You’ll probably find more incorrect usages than correct ones. It’s a solvable problem, you write a wrapper http client once and tell everyone to use it. But it’s a nasty foot gun to have to explain all this.
- Groxx 2y agoI'll just throw in: If you use functional options, please don't implement them with closures. Closures aren't comparable, so there's essentially no way to build middleware that varies behavior based on those arguments. Just make a `type thearg string` or whatever instead. Very similar amounts of code, similarly hidden implementation, but MUCH more usable.
- donatj 2y agoThe lack of default argument values initially annoyed me, but I kind of came to like it. It makes me put more thought into my function interfaces. In the rare cases I do want a default it's usually reasonable to just add a second function that calls the first with the default value. I don't end up doing this a lot, but I certainly have in a couple handful of cases. A lot of Go libraries for HTTP related activities do this with the default context. They'll have a function that accepts a context and a function that has the default context. Example https://github.com/slack-go/slack/blob/242df4614edb261e5f4f4a3907c979caf6b4977c/users.go#L252 https://github.com/slack-go/slack/blob/242df4614edb261e5f4f4... Honestly, with good naming, I think this is just generally more readable and expectable behavior only takes three lines of code.
- mrj 2y agoSure, one can make a new function. That's what I do, too, but then I end up greatly missing function overloading. In the example's case I might end up making a ReplaceAll function. It creates namespace clutter. Function overloading could easily handle context with and without arguments.
- enneff 2y agoI think if there are a lot of functions (or a function with a lot of arguments, common to python) you have clutter regardless. I would rather have a bunch of different names than a bunch of different functions with the same name. Having to choose names for each of the functions is a gentle push back asking “do you really need all these flavours of function or are you abstracting this in the wrong way?”
- wild_egg 2y agoFWIW a lot of those packages with default context wrapper functions have that as a backwards compatibility measure for code written before the context package existed. It's almost always preferable to call the newer function with your own context instead
- wild_egg 2y agoBeen writing Go since 2012 and consider the status quo on all of these to be _features_. I may be in the minority there though
- kbolino 2y agoBeing unable to access struct fields a.b.c without risking a panic sucks (and which caused the panic: a.b or b.c?). There's no remotely ergonomic solution to the problem, because there's no nil-safe struct member operator, there's no ternary operator, and if-statements can't be used as expressions. This wouldn't be such a problem, since of course you can just "choose" to not use pointer- or interface-typed fields in "your" structs, but as soon as serialization, databases, or other people's APIs are involved, you don't have that "choice" anymore. In the same vein, being unable to write e.g. &true or &"foo" is annoying too. If I can write &struct{...} why can't I write &true?
- jen20 2y agoNot being able to take a pointer to a literal is one of my pet peeves with Go - especially when using the AWS SDK, which requires pointers to literals everywhere. At least with generics, a wrapper function doesn't require a separate function per type though, and can be simply: package ptr func To[T any](v T) *T { return &v }
- kbolino 2y agoYeah, that particular case got better with generics. It's still more verbose to write ptr.To(true) than &true though. Unfortunately, there's no generic type constraint for "is an interface" or even "is nilable" so you can't use generics to solve nil-safety issues in general.
- jen20 2y agoIndeed, I see no reason why taking the address of a literal couldn’t be added though, that’s a cheap win.
- SkiFire13 2y ago> While I understand the reason for this (i.e.: to avoid developers relying in a specific iteration order), I still find it weird, and I think this is something unique for Go. Rust's `HashMap` and `HashSet` also do the same with the default hasher (you can plug your own deterministic hasher though). The reason for this choice, which I think also applies to Go, is to be resistant against HashDOS attacks, which can lead to hashmap lookups becoming O(n) on average. This is especially important for maps that will contain data coming from untrusted sources, like data submitted in a GET/POST request. I do agree though that an ordered map would nicely solve the issue.
- kibwen 2y ago> I do agree though that an ordered map would nicely solve the issue. To be precise, Rust does provide an ordered map in the standard library, it's std::collections::BTreeMap. However, iteration order is key comparison order, not insertion order.
- yarg 2y agoIf you want insertion order you need something like a LinkedHashMap. Java's had that forever, but it's not really a common use case.
- rezaprima 2y agofirst time I know of LinkedHashMap is by reading a JSON library (Jason, iirc).
- matwood 2y agoIf you spend any amount of time programming Java, reviewing this list is a big help. https://www.geeksforgeeks.org/collections-in-java-2/ https://www.geeksforgeeks.org/collections-in-java-2/
- SkiFire13 2y agoI personally prefer something like Rust's `indexmap` instead, which is basically a hash table mapping from key to an index into a `Vec` containing the values. AFAIK this is also the approach taken by C#'s Dictionary.
- jmyeet 2y agoHow is Go randomizing the map iteration order? In Java, objects are responsible for their equals/hashCode implementations. The contract they must abide by is: 1. If two objects are equal, they must produce the same hash code; and 2. If they are not equal, they may produce the same hash code. So if you had a list of 10 Strings and put them in a map in Java, it's likely you'll get a deterministic order for iterating over them unless you added a random factor. That factor could be a random seed tied to the map that you XOR the hash code with. You can't really change the hash code itself to avoid a Hash DoS attack because you might break that contract. So how does Go (and Rust?) deal with that? Is Go adding a random seed to each hash map? If not, what is it doing? As for nullability, there's no going back once you use a type system that expresses nullability. Lastly, PHP arrays are incredibly convenient, ignoring the weirdness with them being array and hash map hybrids. But th ekey aspect is that they maintain insertion order when you use them like a map. This is so often what you want. Yes, other langauges do this too (eg Java's LinkedHashMap) but it's (IMHO) such a useful default.
- chowells 2y agoYou don't use the object hash as the key directly. You combine it with a value chosen randomly per-map using a function that works hard to erase correlations between the input object hash and the output table location.
- jhgg 2y ago> Is Go adding a random seed to each hash map? Yes: https://github.com/golang/go/blob/27093581b2828a2752a6d2711def09517eb2513b/src/runtime/map_swiss.go#L311 https://github.com/golang/go/blob/27093581b2828a2752a6d2711d...
- conradludgate 2y agoWhat you do is have a "family" of hash functions. The random seed value chooses a new hash function. The same properties apply to each individual map's hash function, but each map has a different hash function Secondary, go map iteration starts from a random position in the hashmap. The order on subsequent iterations is the same, but rotated as a result of the random start index
- 2y ago
- moomin 2y agoI am constantly criticising the C# community for not looking at other languages enough, but in this case it cuts both ways: C# has every feature mentioned here. Including a pretty good model for nullable.
- Quothling 2y agoI don't think having nullables can be called a feature as such. It adds complexity to your code and it directly goes against Go's philosophy of explicit error handling and simple types. Of course it's completely opinion based but I think having people handle errors directly instead of dealing with them through exceptions and checks makes for much more predictable code. I'm also not sure I really see the difference that GP does. I think that in a lot of code you're going to do a lot of null checks anyway, maybe even more than how often you'll check if your pointers are nil, but at least with Go you're not risking missing one. Maybe the Go engineers didn't think about nullables, but I think there is a good chance they simply decided against them for various reasons.
- moomin 2y agoWe could argue about the Go philosophy till the cows come home, but maybe it would be better to just consider that not having a nullable int makes modelling database tables painful.
- coffeebeqn 2y ago> C# has every feature Yes it does. I just don’t understand why does everyone want every language to be the same language? If you want all the sugar then C#, Java, latest C++ all are perfectly mature and usable and fit that niche
- Xeamek 2y agoBecause languages are more then just syntax, so ofcourse You'd rather have your favorite language copy some syntax you like, then be forced to switch entire stack to another language just to be able to use that syntax
- knodi 2y ago> Nullability (or nillability) > func(s *string) { > // s maybe nil here, better check first > } If this happens, you don't have proper checks before this call. Clearly an error check was missed prior to this call.
- ninkendo 2y agoYou know what's better than having to remember to write the proper checks before the call? Having the compiler do the checks for you. Code that results in a nil dereference should not be compilable, period. Any programming language that allows it is flawed.
- mariusor 2y ago> Any programming language that allows it is flawed. I think any language that allows that has different priorities than complete code correctness. There might even be programmers out there that would also prefer those priorities (simplicity, speed, etc) over having the compiler spend time every compilation to make sure a pointer is null or not.
- ninkendo 2y agoThe amount of time spent every compilation on this is negligible: a nullable type is just another type like any other. I don’t buy your argument at all. It’s a clear no-brainer at this point: null references were a mistake, and any language with compile-time type checking is flawed if they’re allowed.
- mariusor 2y ago> It’s a clear no-brainer at this point Of course. All compiler designers, outside a select few, are clearly wrong and have given the problem absolutely no thought.
- ninkendo 2y agoI mean, the guy who is broadly considered the "inventor" of the null reference straight-up admits he gave it no thought: https://en.wikipedia.org/wiki/Tony_Hoare https://en.wikipedia.org/wiki/Tony_Hoare > At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement So, it doesn't seem unlikely at all that other languages with type systems[0] probably just carried this behavior forward because it's how other languages worked at the time. The idea that you could have references which weren't allowed to be null probably seemed limiting, because other languages allowed it. That this was a mistake is pretty broadly accepted at this point. It's not even a controversial statement any more. [0] I'm excluding languages that don't have type checking at compile time (or without any compile time at all), that's a different discussion. I'm limiting the scope of my criticism to languages that (1) have a compile-time type checker but (2) opt to have that type checker allow null references to be used as if they're non-null.
- coldtea 2y ago>While I understand the reason for this (i.e.: to avoid developers relying in a specific iteration order), I still find it weird, and I think this is something unique for Go. This decision means that even if you don't care about a specific order, you will still need to sort the map before doing something else if you want reproducibility Even if they didn't randomize, unless they also explicitly guaranteed stable map order across versions, you DO need to sort the map if you want reproducibility. Because if you relied on it being conveniently stable within the same Go version, with no guarantees, your program would still be broken (reproducibility wise), if they changed the hashmap implementation.
- dwattttt 2y agoThere was a very insightful comment here on HN a while back; someone noted how terrible some SAP UI for travel was, because it provided a huge list of destinations in random order. The insightful comment said they were sure that whoever was implementing the UI noted the list of destinations was always ordered, so never bothered to sort out themselves. And I guess the data source never guaranteed it was ordered, it was just a coincidence, and one day they stopped providing the list in-order.
- tialaramex 2y agoYeah, that's frequent card creation cause in our systems. Relatively junior (e.g. graduated less than a year ago) engineer is tasked to make a List of Rooms. They write some EF, despite an actual formal course on SQL none of them seems to know the first thing about databases, but they can figure out EF apparently, the EF gives them a list of Rooms and it appears (at a glance) to be right so they commit their work and this ships to our users. The people using the software ask why "8340B" is between "8340D" and "8340E" and the technical answer is "During database changes a year ago, the underlying data was reordered and that's where this record is" but that's not what they mean, they mean "Why didn't you idiots sort the data?" and the answer is well, junior engineer. Of course with a layer of people to decide requirements by the time the card is in my next item pile it doesn't say "Just sort the EF query" - now it's about how we need to adjust the column widths, change to a new colour scheme, and add a checkbox nobody will use... oh, but also can this list be sorted ? So there's an excellent chance if another junior engineer takes that card the sorting gets overlooked and the users assume we can't (rather than don't) fix it.
- karmakaze 2y agoWhen I read 'unordered list', I was thinking it was more than 3 things: - Keyword and default arguments for functions - Nullability (or nillability) - Ordered maps in standard library It's was a play on the hash map iteration.
- kokada 2y agoAuthor here. I never expected this post to get here in HN the way it was. It is definitely a work in progress, most some personal notes that I will probably add more when I use other parts in Go that bothers me.
- kokada 2y agoBTW, I will confess: the orderedmap one is something that I put mostly because I know it is something that would be feasible to implement in a future version of the language and it would probably be relatively uncontroversial. So I was expecting maybe someone will end up doing the work to propose and/or implement this to Go. Who knows, maybe this will work.
- karmakaze 2y agoWith generics being available, couldn't any library implement it without waiting for stdlib to have it?
- kokada 2y agoYes, I did cover this point in the post, but basically the main issue of not having this in stdlib is because now the choice is not obvious: if you search "ordered map for golang" you will find a dozen of different implementations.
- karmakaze 2y agoThat's probably more of an ecosystem culture thing. e.g. Python's culture is that there shouldn't be many.
- qaq 2y agoI think this perfectly illustrates the problem the thing I would most want to see is sum types e.g. we all have some particular thing we would want to add and we can't add em all.
- drdaeman 2y agoNullability is poor man's `Maybe`/`Optional`, and I'd love to see that at the type system level (cf. `data Maybe a = Just a | Nothing`) rather than current {sql,null}.Null* mess or whatever was proposed in https://github.com/golang/go/issues/48702 https://github.com/golang/go/issues/48702. But I doubt if that'll ever happen.
- deleted 2y ago[deleted]
- solraph 2y agoI agree with most of this list, and I'd add some kind of null coalescing or ternary operator, even if it was limited to one operater per expression, and a date time handling library that doesn't make me want to pull.my hair out. There's several things that keep me on Go, single binary, decent built in tooling, and decent speed. I've started playing around with tinygo on Pi Pico's, and after the dealing with getting C and C++ onto other MCUs it's a breath of fresh air. But the rough edges are very rough. At some point another language is going to come along with better syntax with the same single binary and good tooling and I'll probably switch over as fast as possible.
- garyrob 2y agoBorgo is an interesting attempt to address some of these issues. I would love it to get real traction. https://github.com/borgo-lang/borgo https://github.com/borgo-lang/borgo
- 0cf8612b2e1e 2y agoThis looks incredible. I used to write Go, but it always felt like wearing a straight jacket. Too many missing features relative to alternatives, but this fixes a big list of my complaints. I am leery to tap into a new ecosystem, but the risk in this case might not be terrible. Theoretically, you could always take the transpiled code and port to idiomatic Go if the project died.
- garyrob 2y agoYeah. That's similar to my thoughts. But only 2 contributors and no update in 3 months. And there are a number of open issues with zero responses. I'm not in a position to contribute myself. I don't know enough about compiling/transpiling and I have too much on my plate already. So I can't complain, but I'd by happy if more people joined the project and it had more activity. It's exactly what I'm looking for.
- jfoudfwfayasd 2y agoGo with a competent type system would be wonderful
- qaq 2y agoWas really excited when I first found it but it looks abandoned
- neonsunset 2y agoCome here to us in .NET land, we have even smaller AOT binaries, nullability and better systems programming story. And type unions, whenever they come around in one of the next releases.
- akdor1154 2y agoNillability is the biggest thing that drives me to write 'unidiomatic go': there are a few Optional libs around, they work ok. I write with the following rule: if a pointer is passed, it shouldn't be nil. If it might be nil, code it as an Optional<> instead. Un-golike but works great.
- hellcow 2y agoI define my own Null[T] for this purpose. There's sql.Null in the stdlib already, so that seems plenty go-like.
- autarch 2y agoWe have started doing this at work as well. It makes the code a lot easier to understand, and I think it's worth the small hassle that this entails (because without a `match` statement, dealing with an Option type is verbose).
- Neikius 2y agoThis is actually terrible. I tried that a while ago, but after a short while removed all of the Optional[] code and went back to pointers. Why? The default ser/des in go just cannot play. It instead works great with pointers. Using pointers that are nillable whenever I want to have an optional value. How did I solve the usability problem? I just introduced 2 simple methods: Or and Of. First one will resolve ptr to a value or default if nil (provided in param) and the second one will make a ptr from a value type. That is actually all you need! Don't have the code here or I'd post it but it's easy enough to make your own (with generics).
- jjdhxhbe 2y agoUsing a pointer in go can mean two things and I don't like it: - Value can be nil - Value is mutable It's neither possible to have a const but nilable value as well as it's not possible to have a non-nilable mutable value
- aaomidi 2y agoI really dislike default values because it adds one more location where a value can be different from what id expect. Honestly, be explicit rather than hoping for implicit behavior.
- gregjor 2y agoI haven’t found these specific things annoying. PHP has all of the features listed in the article. Not saying anyone should choose PHP over Go.
- pansa2 2y agoI've heard this several times - "Go would be great if only they added <my-favourite-feature>"... Go's philosophy is that a coherent, curated feature set is as valid an approach to language design as the C++/Python/... approach of adding every possible language feature. In particular I doubt Go will ever add null-safety - given the above philosophy, the language's pervasive use of "zero values", and its strong commitment to backwards compatibility.
- EdwardDiego 2y agoHow do you distinguish between a value set to zero value explicitly, and one not set?
- jochem9 2y agoThere is no difference. You need to handle that based on the context you're in.
- EdwardDiego 2y agoI was wondering if there's a pattern of using Option types or something to signal the difference. I ask because I hit this issue a fair few years ago with protobuf v3, we ended up using a wrapper type pattern. Can't recall why it was important to know at the time, but it was.
- the_gipsy 2y agoSometimes you can abuse pointers as a (very) poor man's Option<T> type. But it's turtles all the way down, you can't distinguish between for example `null` and "missing" when parsing JSON.
- mervz 2y agoYikes...
- kzs0 2y agoIn the cases where this is important, you can use pointers. Go allows you to make pointers to primitives as well (making the zero value nil) so you can explicitly define those edge cases. You’d be surprised how infrequently that’s actually a concern though.
- everybodyknows 2y agoAm I the only one who feels the absence of a slice type strictly checked by both index and content?
- tsimionescu 2y ago> Go isn't different, it has map, that is Go implementation of a hash table. It's a bit nitpicky, but this always annoys me. Maps/dictionaries are not hashtables. A hashtable is one of the structures you can use to implement a map. A hashtable stores arbitrary items, not key-value associations, and can be used to quickly retrieve an item knowing its hash. If you want to implement a map using a hashtable, you need to also define a type that wraps a key-value pair and handles hashing and equality by only comparing the key. Also, maps can be implemented with other underlying data structures as well. Java's standard library even offers a built-in TreeMap, which uses a red-black tree to store the pairs instead of HashMap's hashtable.
- valyala 2y agoI'd like to remove generics and iterators funcs from Go, and stop adding programming language shit to Go. https://itnext.io/go-evolves-in-the-wrong-direction-7dfda8a1a620 https://itnext.io/go-evolves-in-the-wrong-direction-7dfda8a1...
- WesolyKubeczek 2y agoYou are free to not use them.
- valyala 2y agoI cannot, since others will use them. So eventually I need to deal with the over-engineered overcomplicated shitty code, which uses these "features".
- dawkins 2y agoI agree. The limited expressiveness in Go also worked as an advantage because of its simplicity. Additionally, as the article mentions, the lack of lambdas made the syntax less convenient. For me, it struck a good balance before generics and other features were added.
- DandyDev 2y agoI’m not convinced that limiting expressiveness (for example by not supporting generics) will make software easier to read and maintain. For smaller programs that might very well be true, but for me personally, having more expressiveness makes it easier to navigate bigger code bases because you don’t have to trudge through code duplication, unnecessary boilerplate etc.
- valyala 2y agoGenerics in Go have been appeared in 2022 (in Go1.18). There were many popular open source projects with big code bases written in Go before 2022 - Docker, Kubernetes, Prometheus, Caddy, InfluxDB, etcd, minio, Terraform, CockroachDB, Consul, Helm, VictoriaMetrics, etc. The absence of generics didn't prevent from writing and maintaining these projects. I'm unaware of popular projects in Go, which have been appeared after 2022 thanks to generics.
- kitd 2y agoI disagree with having the ordering embedded into the map implementation. That imposes an unnecessary performance overhead to support a small subset of use cases. I think what the author requires is iterating over a sorted list of keys. That is pretty easy to implement using the standard library, and imposes the performance penalty only when it is needed.
- DandyDev 2y agoThe author is not saying that ordering needs to be added to the _current_ map implementation. He suggests adding an additional map implementation that has ordering built in. That way, you can choose between functionality and (hypothetical) better performance The author does not seem to require iterating over a sorted list. Sorting is not the same as ordering. An ordered map is a map in which the insertion order is preserved when iterating over the elements. A sorted map outputs the elements in an order defined by a comparison function when iterating, regardless of their insertion order. You can for example sort alphabetical in case of string keys.
- deleted 2y ago[deleted]
- masklinn 2y ago> I disagree with having the ordering embedded into the map implementation. Good thing that's not what they are asking at all. They just want an ordered map to be in the standard library. > That imposes an unnecessary performance overhead to support a small subset of use cases. Naturally ordered hash maps generally have a small performance hit on lookup and a performance gain on iteration, as iteration goes through a dense array. Linked hash maps do tend to have worse performances for all cases. > I think what the author requires is iterating over a sorted list of keys. Had they needed that, they'd have said that. But they did not. And they specifically refer to an ordered map, and to Python's built-in and Ordered dicts, which are not sorted.
- gizmo 2y agoIn most cases the performance penalty of having an extra internal array to keep track of insertion order is minimal, and the whole point of built-in collections is so people can quickly write correct programs. When optimizing for performance default collections are likely to get replaced with hand-rolled versions anyway. But in all other cases a dictionary that “just works” is preferable to one that has such an annoying footgun that the go team had to randomize the iteration order in an attempt to treat the symptom instead of choosing correctness. Go isn’t even a high-performance language and many language design choices (channels!) explicit prioritize correctness over performance. It’s like having an unstable sort as the default standard library sort function. People reasonably expect that when calling sort twice the second sort to do nothing, but you can always find people who will passionately argue that people deserve to get burned if they assume a sort function is stable.
- daghamm 2y agoI too have a list of things I want to add to Go. For some reason, my list and OPs list are completely disjoint. My wishlist is: 1. Add the ? operator is a short hand for if err != nil { return ..., err } 2. Allow member functions to have generic parameters (in addition to the struct parameters)
- mervz 2y agoStreamlining the awful error handling would seriously make the developer experience SO much better... but this is Go, where developer experience comes dead last in priority.
- jessekv 2y agoMaybe I like the pain and I don't know it, but the overall DX is why I keep coming back to Go.
- daghamm 2y agoIn general Go DX is fantastic. But having done some Rust development lately, I really miss the ? thing every time I go back to golang. It's such a small change and purely syntactic but ould make ones code much shorter and maybe even more readable.
- jessekv 2y agoI suspect the reason why so many people are passionate about Go language features is that, if it only had their one pet feature, it would be the perfect language. But I agree that the error handling could be better!
- nu11ptr 2y agoAfter getting used to Python's dicts being ordered since 3.6, I really wish every language would do this. I think it is natural to think about the keys being kept in inserted order, and it is very handy a lot of the time. Rust's `indexmap` for example is nearly as performant if I recall as the stdlib `HashMap`, so it probably wouldn't be much in the way of overhead to do so. Regardless, every major lang should have an ordered map in the stdlib in my opinion.
- largbae 2y agoI wish that an unhandled error would crash its way up the stack automatically returning error if the next function up can do so, until it is either caught into a variable or can't be returned (panic if error can't be returned). This would get close to python try/catch with even lighter syntax. This would cut so much boilerplate hand carrying error up the stack.
- 38 2y ago[flagged]
- assbuttbuttass 2y agopanic() already exists
- kokada 2y agoI talked in my previous post (https://kokada.capivaras.dev/blog/go-a-reasonable-good-language/ https://kokada.capivaras.dev/blog/go-a-reasonable-good-langu...) that nowadays I just implement a generic `must*()` family of functions that can be used as: func must(err error) { if err != nil { panic(err) } } func must1[T any](v T, err error) T { must(err) return v } func maybeError() (bool, error) { ... } result := must1(maybeError()) And this generally works fine 99% of the time when I just want a stack trace on error. So this is why I don't care that much about having a syntax sugar for this operation anymore in Go.
- daghamm 2y agoThis is not error-handling :) In fact, this is the opposite of error handling. In any serious application this might be worse than ignoring errors
- kokada 2y agoI didn't say this is error handling, this is a stack trace for debugging on error. Similar to an uncaught exception in other languages. And yes, I will not use this on production applications or libraries, I mostly use this in scripts where this kind of thing makes sense.
- coin 2y agoUsing Go, I miss enums
- MarkMarine 2y ago“I don't think the language needs to support the generic solution for nullability, that would be either having proper Union or Sum types.” - then goes on to describe some of the problems sum types would solve. Why. Why doesn’t go need this? It was just presented as a blanket statement without a reason. Personally, I see missing sum types as a major gap, and I reach for them all the time in other languages.
- kokada 2y agoI didn't develop too much because as I said in another thread, I wrote this post without giving much thought. Sorry for not being at the HN standards, but this post wasn't even supposed to be here, and here we are ;). That said, I think given the current state of the language, adding nullability would be much easier to do than adding Union or Sum types. And from my experience with Kotlin, nullability already gives much of the benefits. I am not saying I will not change my opinion in the future. I got my first job working with a language that has algebraic types (Scala), so my opinion may change in future. However, even if it changes I think getting Union or Sum types in a language like Go is impossible, while nullables are unlikely to happen but at least not impossible.
- MarkMarine 2y agoI don’t follow. Why would getting sum types in go be impossible? There is already a proposal for this: https://github.com/golang/go/issues/57644 https://github.com/golang/go/issues/57644 The generic type params already supports a sum type like interface, it’s almost there. So, if you could, please expound with on “why” Is there something in the type system, something in the compiler that prevents it? Anyway, re: not up to HN standards… I’m not sure what you’re talking about. You made it to the front page, you called out some legitimate issues, I liked reading what you had to say, I was just asking for more
- kokada 2y agoI think I recommend you reading the proposal them. I don't claim of being a specialist in Go to say if it is possible or not, but I find it highly unlikely given how the language is. The reason I think nullability is more likely than sum types is because Go tries to be a simple language (whatever the developers of the language think simple is), and nullability is simpler than sum types (both to implement and use). But again, I don't have any special insight
- wwarner 2y agoI guess i don’t care very much about the “ergonomics”, like sorted hashes or whatever. I’d be really happy with faster execution, smaller memory footprint, smaller binaries. Conditional compilation would be great, but maybe smart utilization of code generation is sufficient here. For me the glaring gap i suffer with is data processing and ML, which is a community/library thing.
- malloc-0x90 2y agoI am noob with Go, trying to learn it lately for more rapid development, and I'm coming from C. I'm currently using LiteIDE, any good soul could suggest how what plugin to install in Zed, or Lapce, or Pulsar ? (Unfortunately I refuse to use VS Codium because microsoft, and NeoVim because IBM CUA keybindings)
- pancsta 2y agoI dont agree with even 1. Especially the yield example is very naive.