Better HN
topnewbestaskshowjobs
Log inSign up

Merovius

729 karma · joined Jun 14, 2015 (11y ago) · 258 submissions

Submissions

comment 1y ago · link · parent

> C++ templates are duck typed at compile time.

"Compile time" is not the right distinction. This is about "instantiation time". Go's implementation specifically allows to type-check the body and the call separately. That is, if you import a third-party package and call a generic function, all the type checker needs to look at to prove correctness is the signature of the function. It can ignore the body.

This is especially relevant, if you call a generic function from a generic function. For C++, proving that such a call is correct is, in general, NP-complete (it directly maps to the SAT problem, you need to prove that every solution to one arbitrary boolean formula satisfies a different boolean formula). So the designers made the conscious decision to just not do that, instead delaying that check to the point at which the concrete type used to instantiate the generic function is known (because checking that a specific assignment satisfies a boolean formula is trivial). But that also means that you have to (recursively) type-check a generic function again and again for every type argument provided, which can drive up compilation time.

A demonstration is this program, which makes gcc consume functionally infinite amount of memory and time: https://godbolt.org/z/crK89TW9G (clang is a little bit more clever, but can ultimately be defeated using a similar mechanism).

Avoiding these problems is a specific cause for a lot of the limitations with Go's generics.

> Look at Haskell type classes or Rust's traits for some classic examples of how to 'type' your generics. (And compare to what Go and C++ are doing.)

Yes, those are a different beasts altogether and the differences between what Go is doing and what Haskell and Rust are doing requires different explanations.

Though it's illustrative, because it turns out Rust also intentionally limited their generics implementation, to solve the kinds of performance problems Go is worried about. Specifically, Rust has the concept of "Dyn compatibility" (formerly "Object safety") which exists because otherwise Rusts goal of zero-cost abstractions would be broken. Haskell doesn't have this problem and will happily allow you to use the less efficient but more powerful types.

(All of this should have the caveat that I'm not an expert in or even a user of any of these languages. It's half-knowledge and I might be wrong or things might have changed since I last looked)

comment 1y ago · link · parent

> Maybe when you have code that works with the `interface{}` a lot (e.g. unknown JSON data) you'll have a use case for it.

I think in those cases, generics are specifically kind of pointless. Because you will inherently need to use `reflect` anyways. Generics are only helpful if you do know things about your types.

Generics are most useful for people who write special-purpose data structures. And hence for people who need such special-purpose data structures but don't want to implement them themself. The prototypical example is a lock-free map, which you only need, if you really need to solve performance problems and which specific kind of lock-free map you need depends very heavily on your workload. `sync.Map` is famously only really useful for mostly write-once caches, because that's what its optimized for.

The vast majority of people don't need such special-purpose data structures and can get by just fine with a `map` and a mutex. But Go has reach the level of adoption, where it can only really grow further, if it can also address the kinds of use-cases which do need something more specific.

comment 1y ago · link · parent

I don't disagree that Go's generics are pretty limited. But I find it a strange complaint, when contrasted with C++ templates. Which, as I understand, are literally not part of the type system and thus there seems to be a far stronger case, that they can not be called generics.

The main difference between Go's generics and C++ templates (and where some of the restrictions come from) is that Go insists that you can type-check both the body of a generic function and the call to it, without one having to know about the other. My understanding is, that with C++ templates (even including concepts), the type checking can only happen at the call-site, because you need to know the actual type arguments used, regardless of what the constraints might say.

And this decision leads to most of the complaints I've heard about C++ generics. The long compile times, the verbose error messages and the hard to debug type-errors.

So, if you prefer C++ templates, that's fair enough. But the limitations are there to address complaints many other people had about C++ templates specifically. And that seems a reasonable decision to me, as well.

comment 1y ago · link · parent

In practice, currently, that depends on inlining decisions. If the function taking the function (say `node.insert`) is inlined, then yes. There are also other optimizations, like escape analysis, that matter here: the compiler can prove that the arguments to `node.insert` only escape into the `cmp` passed in. That decision is kept as metadata on `node.insert` even if it is not inlined. So if you pass a method expression to it, it can actually look at that and decide that the arguments don't escape from it either and hence that they don't escape overall. Whereas if you pass a `func` field, it can make no assumptions.

My larger point though, is that with the `func` field the compiler can't optimize things even in principle. A user could always reassign this field (if nothing else using `*t = *new(FuncTree)`). So the compiler has to treat it as a dynamic call categorically. If the `func` is passed as a function, then at least in principle, it can prove that this function can't get modified during the call so can make optimization decisions based on what is being passed to it. For example, even without inlining, a future compiler might decide to compile two versions of `node.insert`, one with general dynamic calls and one specific one for a specific static function.

My philosophy when it comes to API decisions that impact performance is, not to make them too dependent on what the compiler is doing today, but just to take care there is enough information there, that the compiler can do an optimization in principle - which means it either will do it today, or we can make it smarter in the future, if it becomes a problem.

comment 1y ago · link · parent

> I didn't realize how important order was to type inference.

I was unclear, I'm afraid. You can reorder the type parameters, it just changes which of them you need to specify: https://go.dev/play/p/oDIFl3fZiPl

The point is that you can only leave off elements from the end of the list, to have them automatically inferred.

> Are there any real packages out there using these techniques?

I think so far, the usage of generics for containers in Go is still relatively sparse, in public code. I think in part that is because the documentation of how to do that is relatively sparse. That is part of the motivation for the post, to have a bit of somewhat official documentation for these things, so they become more widely known.

The standard library is just starting to add generic containers: https://github.com/golang/go/issues/69559 And part of that is discussing how we want to do things like this: https://github.com/golang/go/issues/70471

That being said, I have used the pointer receiver thing in my dayjob. One example is protobuf. We have a generic helper to set a protobuf enum from the environment. Because of how the API was designed, that required a pointer receiver constraint.

36.

Generic interfaces(go.dev ↗)

58 points · by Merovius · 1y ago · 76 comments

comment 1y ago · link · parent

Oh and to be clear: I didn't say "look at this issue, most people clearly prefer the status quo". I just said that given this issue, making the claim that the status quo is objectively bad is hard to justify. I said that its badness is clearly subjective.

That is, I criticized the strength of the original claim. I didn't try to make an equally strong opposite claim.

comment 1y ago · link · parent

> (that is the reason the people spend years to solve it)

I don't think anyone actually spend years trying to solve it. It's just that over the years, many people have tried to solve it - each for a grand total of maybe a week or so. If you look at the list, you'll see a lot of different proposal authors: https://seankhliao.com/blog/12020-11-23-go-error-handling-pr... Most of these do not post any other issues and many of those don't even respond in the discussion to their own proposals.

It's a thing that a lot of people coming to the language get frustrated by, think "here is an obvious way to make this better" and file a (usually half-baked) proposal about. It's not a thing that people spend years of focused effort on to polish into something that works.

Compare that to generics: Not only did Ian file a proposal about that roughly every year. The final design also had over a year of intense discussion, with at least a dozen or two consistent participants (and a hundred or so occasional ones). With at least three or four direct iterations.

Error handling is something that a lot of people care a little about.

comment 1y ago · link · parent

It doesn't really contradict the survey all that much. 13% of respondents said that error handling is the biggest issue. That leaves 87%, which can rank anywhere from "it's an issue, but not the biggest" through "it's a minor nuisance" through "I don't care" up to "I actively like the status quo". We can only guess about the distribution.

And yes, I agree that the survey is a better source of data, generally. But I will also say that it intentionally asks as broad a definition of "Go user" as possible. Meaning it also (intentionally) asks people who might use Go every once in a while at work. And a good chunk of respondents are newcomers. These groups are more likely to identify this as a problem. While people who are active on GitHub tend to bias towards people who use it as a daily driver and are much more used to its idioms.

The data is mixed. I fully acknowledge that. But anecdotally, there seems to be a pretty clear pattern that people who come new to the language complain about this, but then get used to it and at the point where they become active in the community, they prefer the status quo. I don't think the experience of newcomers should be dismissed, but I also think it should be acknowledged that it's something most people get used to.

comment 1y ago · link · parent

> But is know that the current way of Go (that is a insignificant improvement over the C way) sucks and ANY of the other ways are truly better […]

This is a bold statement for something so subjective. I'll note that the proposal to leave the status quo as-is is probably one of the most favorably voted Go proposals of all time: https://github.com/golang/go/issues/32825

Go language design is not a popularity contest or democracy (if nothing else because it is not clear who would get a vote). But you won't find any other proposal with thousands of emoji votes, 90% of which are in favor.

I get the criticism and I agree with it to a degree. But boldly stating that criticism as objective and universal is uninformed.

comment 1y ago · link · parent

Except if your traits are not dyn-compatible. Which I believe a lot of Rust's traits are not. That restriction is specifically why Go does not allow methods to have extra type parameters: To make it possible for the language implementation to choose its own tradeoff between monomorphization and boxing.

So I don't think you can say that this has nothing to do with the type system. Here is a restriction in the Go type system that was specifically introduced to allow a broad range of implementation choices. To avoid being forced to choose slow compilers or slow code: https://research.swtch.com/generic

The Go type system and the way it does generics is directly designed to allow fast compile times.

comment 2y ago · link · parent

I can blame the evil overloads for building a monopoly which then becomes a juicy target for scammers. Just like block chains are effectively "the mother of all zero-day bug-bounties", so are monopolies the mother of all algorithm-exploitation bug-bounties.

comment 2y ago · link · parent

A supplementary post to my talk at GopherConAU 2023, about a design problem with NP-completeness encountered in the discussions about Go generics.

44.

Constraining Complexity in Go Generics(blog.merovius.de ↗)

4 points · by Merovius · 2y ago · 2 comments

comment 2y ago · link · parent

That depends. C function call overhead for Go is quite large (it needs to allocate a larger stack, put it on its own thread and prevent pre-emption) and possibly larger than for CPython, which relies on calling into C for pretty much everything it does, so obviously has that path well-optimized.

So I wouldn't be surprised if, for some use cases, Python calling C in a tight loop could outperform Go.

comment 2y ago · link · parent

> its creators explicitly said their goal was to replace C++

I think that is a far clearer goal if you look at C++ as it is used inside Google. If you combine the Google C++ style guide and Abseil, you can see the heritage of Go very clearly.

comment 3y ago · link · parent

The Author of this article is the founder of a startup trying to make "cultured oil" happen. Not a particularly trustworthy and neutral source for "the studies".

He's certainly not going to be very motivated to tell y'all about studies showing that he is staking his time and money and reputation on a nonsense product. It's embarrassing that y'all upvoted this.

comment 3y ago · link · parent

> I'm also slightly concerned over how blase "hackers" here on this site are treating the news. All around us are these huge, easy-to-abuse, global influence platforms with cozy backchannels to the most powerful bureaucratic state (US govt) that we've ever seen. And yet many comments I've seen so far are along the lines of, "No worries, this stuff happens all the time and is totally normal and okay. Move along now!" I would have expected more skepticism, cynicism and backlash from this crowd. Am I wrong?

I don't think you are wrong. I do think this is a powerful tool, that should be scrutinized. But I also can't think of any better alternative. So, in the meantime, ISTM that talking about how it's talked about (as a great conspiracy and revelation, when it's well-known and the best known solution to a problem we have) seems the right way to go about it.

And note that not so long ago Musk himself said that this solution is what he wants for Twitter¹.

I just think when talking about the "Twitter Files", the more interesting story is how Musk is spreading disinformation and propaganda to increase his own wealth and power and how supposed journalists are uncritically helping him do it.

[1] https://twitter.com/whstancil/status/1601020232994201601

comment 4y ago · link · parent

> In both cases, the proof is the same: “email verification” means “the user controls an email address.”

No. In one case the proof is "the user receives E-Mails under this address" and in the other it is "the user can send E-Mails under this address".

The service is generally interested in proving the first. For recovery, service-related notifications and for unsolicited marketing. So all the things mentioned in making the "normal" flow undesirable, are actually exactly what the service owner wants to protect against. If their E-Mails don't get to you because they end up in spam or just get dropped by a misconfigured Mailserver, they can't spam you and you won't be able to use this account for recovery.

I agree that the reverse flow is easier (though TBF, mailto links also require the user to have set them up to work, which not all users have on all their devices). But I don't think that's where the incentives align.

comment 4y ago · link · parent

Even though you are being snarky and intentionally obnoxious: I even thought about that, yes. If unicode would allow to use red and green as skin tone modifiers, I would've done it. Except I probably wouldn't have used red and green, but red and blue or something. Because color blindness is a thing.

Look, I accept the criticism that the table is a bit hard to read. I thought about it and it's still the way I like it best. And it's the most low-stakes thing possible. It doesn't matter if it is slightly hard to read. It's my personal blog. "I like it best this way" is enough said.

comment 4y ago · link · parent

I considered both. The issue I'm having is that "yes" and "no" is semantically wrong - or rather, semantically uninteresting. The interesting question is if a particular mechanism is "good" or "bad" in a particular way. For "boilerplate types", a "yes" is bad. For "custom order", a "yes" is good.

Writing "yes" or "no" (or using checkmarks and crosses) means I either have to put it on the reader to do that extra step of inference. Or that I have to re-phrase every item to be aligned in this way, while staying snappy. Or I could write "good" and "bad", of course, which seemed… overly simplistic.

Anyways, I did think about all of this and it was a conscious decision. For better or for worse. And I'm okay with it, criticism notwithstanding :)

comment 4y ago · link · parent

Personally, I very much dislike that this makes the zero value of `SearchTree[T]` not useful. I personally feel that anything which only handles data (as opposed to something like an os.File) shouldn't require explicit initialization.

I genuinely think I might personally converge on the `Comparator[T]` approach only (at least for types), for that reason.

comment 4y ago · link · parent

Note that the article targets people writing generic code, not consuming it. So it's not really about what you want to sort. It's about what (and how) you want to support with your sorting algorithm.

As for that use-case: Go generics currently don't have a way to constrain on struct fields. So that will always have to be done with some sort of custom comparison function written by the user of your code, which returns the appropriate field.

comment 4y ago · link · parent

> How do float32 and float64 satisfy constraints.Ordered?

Well, the simple answer is that constraints.Ordered is a type set which lists them: https://pkg.go.dev/golang.org/x/exp/constraints#Ordered

The other answer is of course, that float32 and float64 have a < operator, so every type listed in constraints.Ordered does, so you can use the < operator on a type parameter constrained by constraints.Orderded.

The real question you seem to be asking though, is "how does Go support < on float32 and float64 if the IEEE-754 standard says that NaN are not comparable". I can't comprehensively answer that, because I don't know that standard well enough. But for == the answer is that == is supported on floats and x == y is always false if either is NaN. Empirically, the same seems to be true for NaN <= NaN: https://go.dev/play/p/hB9CnrzpAVq

In any case, Wikipedia claims that IEEE-754 defines in fact an ordering, which is the one Go is going to use use: https://en.wikipedia.org/wiki/IEEE_754#Total-ordering_predic...

55.

Operator constraints in Go(blog.merovius.de ↗)

47 points · by Merovius · 4y ago · 18 comments

comment 4y ago · link · parent

> So far, Rust seems to have gotten it right by essentially copying Haskell.

FWIW I've used Rust for a bit and I disagree that they "got it right". I'm not saying Rust is bad, I like the language. But it's not as if their generics implementation does not have issues. It's just that they are different issues.

comment 4y ago · link · parent

> It is indeed accepted if it's there by itself, but it is rejected if you try to use the interface, which is what function f does:

You can't use it as a type, but you can use it as a constraint: https://go.dev/play/p/LnmudHIjAoQ

Of course, you can then not actually instantiate that function (as the type set is empty). But using concrete types in interfaces is very possible. And it's indeed why the |-operator was introduced. It allows you to use operators: https://go.dev/play/p/I3eMDBwIcHA

comment 4y ago · link · parent

> To be clear here, the tradeoff being made is that it is more important that the compiler is fast than that it is able to tell programmers about clear bugs in their code.

I'm not sure that's entirely true. Or it seems at least misleading.

"Fast" here means "guaranteed to finish before the heat death of the universe", in the worst case.

And as I'm trying to explain in the post, it is easier to explain clear bugs to the programmer, if you don't have to rely on solving NP-complete problems. NP-complete problems are notoriously hard to report errors for, which the user understands.

comment 4y ago · link · parent

There are two reason why the compiler would need to check: 1. Because it makes for a better developer experience, if you get early feedback about your code being wrong. And 2. because type-checking a generic function requires you to check that an operation is allowed for all types in a type set. If you write func F[T C](a, b T) T { return a + b }, the compiler needs to check that all types in C have a + operator. If the type set of C is empty, then that's true - all types in the empty set have the + operator.

60.

Calculating Go type sets is harder than you think(blog.merovius.de ↗)

79 points · by Merovius · 4y ago · 40 comments

12345
9