Leveraging the Go Type System
gopherguides.com
gopherguides.com
So far I still haven't found a clean way to have proper enums, and this article shows us that unfortunately neither the author has :(
I love Go for many decisions that have been made during its development, but the handling of enumerations is certainly not part of it.
X interface{} // int(3) | int(5) | []float64 | *Z
It sucks.It's not great for a number of reasons. First of all, `nil` is always a valid permutation even if we don't want it to be. Secondly, it's a lot of work to express the constraints we want. Thirdly, it's not perfectly type-safe; someone who was determined to shoot themselves in the foot could construct other instances of our "singleton types" if they really wanted to. Fourthly, boxing all of these values will almost certainly cause unnecessary allocations which would be a bummer if we wanted to create a lot of these quickly (this is an implementation detail and may not be any worse than a language with first-class support for sum types).
data Genre = Adventure
| Comic
| Crime
| ...
deriving (Show)The same is true for a `Genre(0)`, which is easy to make by accident with just a `var genre Genre` declaration (that's a `Genre(0)` already). Or by ignoring an error return, like in `json.Unmarshal(data, &genre)` (that func returns an error, but that fact is invisible in text, and you are not required to assign or handle it. fun for code reviews!).
You can also have a Genre-arg func like `func GenreToString(g Genre) string` and call it with `GenreToString(12345)` and that'll also compile.
---
Go does not have anything even remotely like enums. It has a short-hand for auto-incrementing constants, nothing more. As if that were somehow the most valuable part of constants / enums.
On the one hand: Good language support for a specialized type and a method on that type, without making the type a heavyweight class (i.e. all that magic can happen at compile-time; Genre can still be an int "under the hood").
On the other hand: wow, that's a lot of boilerplate to write just to get the string representation of a token the compiler already knows about. As other commenters have noted, `go generate` will decrease the amount of code that needs to be hand-written, but it still smells like something the language should handle without explicit code.
Although we did survive with them and delivered code into production, it doesn't mean we keep using them 20-30 years later.
It's not perfect, but it's among the best. It's far better than the popular offerings for Python, C, C++, and Java. NPM was also pretty terrible last I used it (needed to regularly blow away node_modules and reinstall things, random ENOENT errors, etc) and I think the .net world almost adopted a sane project file structure before reverting back to MSBUILD but I might be wrong there. OCaml was also pretty terrible last I used it, but people swear to me that Dune has fixed everything (though those guys have been telling me for the decade that no one needs shared memory parallelism and also it's right around the corner, so maybe take that with a grain of salt).
> The tooling is also sub-par for modern languages, especially in terms of free development environments, though go-pls is slowly improving.
Go doesn't have great IDEs because it's always been more of a text-editor language, and few languages have editor plugins of comparable quality. It also doesn't have a great debugging story (there is Delve, but I've heard that it's not a great debugging experience). These don't really chafe me because I don't like IDEs and I'm the unpopular guy who hates debuggers. Those are the biggest "gaps".
For other things though, Go is great. Testing? Built in. Benchmarking? Built in. Profiling? Built in. Cross compilation? Built in. Static linkage? It's the default. Formatting? Built in. Documentation generation? Built in. Code and documentation packaging and publishing? Built in (to git). Not only are all of these things built in, but they're standard across the ecosystem so developers can onboard with minimal learning curve.
Maven is significantly better than Go modules: it doesn't require special support from your git server, it doesn't rely on magic tags with magic formats, it does strict dependencies by default, it handles branching any way you want, it works with binary artifacts not just source code, it has explicit support for custom repos, it doesn't require renaming your package to do a major version upgrade, it doesn't rely on DNS for package names, it works for small cross-language dependencies, and probably others.
> For other things though, Go is great. Testing? Built in. Benchmarking? Built in. Profiling? Built in. Cross compilation? Built in. Static linkage? It's the default. Formatting? Built in. Documentation generation? Built in. Code and documentation packaging and publishing? Built in (to git).
Testing is actually pretty bad, go test is OK, but the lack of any kind of basic testing tools like a deep equality or mocking helpers make it much harder to use than most. Code coverage measurement is also pretty bad, and un configurable.
Benchmarking is decent, it's nice to have it built in, no complaints there.
Profiling is horrible, just some text format that's barely documented, no memory dumps, no thread bases profiling, no tooling to analyze complex profiles.
Cross compilation is nice, but it's not even required in the most direct competitors (Java, C#).
Static linkage is the only option, and neither a good nor a bad feature.
Formatting is forced on everyone, and is completely unconfigurable. Their choices often mess up for merges for stupid anesthetic reasons.
Documentation is built-in to Java and C# as well, and it supports more than basic text for describing your code. They also don't rely in any way on your choice of source control system.
Overall, Go's ecosystem is definitely sub par compared to Java or C#. It's not the worse, and it can do the job, but you'll never be as productive.
Their support for small fats starting binaries is the only thing where Go really shines.
Also, as far as I know, Go doesn't require special support from your git (or whatever VCS you use) server, as is confirmed by the reference: https://golang.org/ref/mod#vcs
Though I mainly wanted to comment on the profiles part. Could you please provide links to tools which are in your opinion good for complex profiling use cases?
I'm asking because I myself really like both the web based profile viewer, as well as the go tool trace viewer, for more complex situations.
However, to address the other points: testing has good libraries for equality and mocking (I.e. testify); formatting is a trade-off, many people prefer one forced consistent code style, even if they don't like it
Overall, your conclusion of the Go ecosystem being "definitely worse" looks quite far fetched based on your arguments. Not to say it's wrong, the reasoning just isn't at all convincing.
One point of clarification- pretty much no one uses the VCS qualifier (.git in the module path) so the nicer looking import paths work by having a web server respond with the special meta tag. That could be what OP was referencing.
Also, tangentially, Drew DeVault found out that the docs hosted on pkg.go.dev only use a whitelisted set of domains for sources.
I really do enjoy Go, but there are several examples of things like enums that are left out because there is some way of doing it otherwise to only the theoretical advantage of “elegance” at the cost of developer productivity.
It also doesn't touch on the other useful "system" funcs to include on a type (Scan, Value, Marshal, etc)
I didn't go into any of the Scan/Value/Marshal etc as it was a little beyond the scope of this article. I can certainly do a follow up article on it though
Thanks for the feedback!
* yes I know time.IsZero() is a thing, and the semantics are similar, but I want the compiler to warn me if I'm trying to use a time without checking if it's actually initialised first.
It needs sum types and pattern matching. Once you have used them, not having them is a huge gray void. Const expr, interfaces, sum types and pattern matching get you 85% of the way there.
I think it'd make more sense to just make a idiomatic struct:
type Genre struct {
id int
name string
}
func New(id int, name string) Genre {
return Genre {id, name}
}
Then, you can define your categories normally: var (
Adventure = genre.New(1, "Adventure")
Comic = genre.New(2, "Comic")
// etc
)
And have a O(1) String() method that doesn't need to be edited every time a new category gets added/removed/changed: func (g Genre) String() string {
return g.name
}
You can also change the implementation of the type without breaking consumers (e.g. maybe you want a pointer to a struct instead of a struct)This also means that you don't accidentally leak an "is-a" relationship between the nominal type and the underlying implementation type
var foo Genre = Adventure
foo + 1 // ought to throw a compilation error!> var (
> Adventure = genre.New(1, "Adventure")
> Comic = genre.New(2, "Comic")
> // etc
> )
Yet there is nothing preventing anyone from reassigning Adventure to genre.New(2, "Comic") or some other arbitrary value. The fact that golang doesn't have the equivalent of Java's `final` is just poor design.
Secondly, `final` serves as strong and clear documentation. We know just from looking at the definition that this is variable is not going to be re-bound.
On a side note, this compiles in golang:
func main() {
true := false
if !true {
fmt.Println("wat")
}
}It's highly unidiomatic to mutate bindings from libraries in any language, even ones that technically allow you to, so the observation that go is one of those languages feels like nitpicking at obscurities.
My Java is rusty, but I recall that several years ago I ran into some stuff in the Java core API that was needlessly marked final requiring some nasty wrapping around a huge class to get around. Trade-offs, trade-offs.
Yes, but a good language is supposed to minimize chances of error, especially one that was designed after C, C++, and Java. The industry progressed, and we have a better understanding of what some good ideas are, and which to avoid. The fact that golang allows null pointers is inexcusable IMO. C# was able to retrofit a nullable handling mechanism into the language, and practically any useful language that was designed after that had some sort of nullable type handling (Scala, Kotlin, Rust, and I believe Zig and Nim as well, etc.).
That Java dropped C++-style `const` is also poor design.
We're just all really bad at this.
I think that Rust's approach is superior to C++'s here, but even that has some issues so they have to retort to interior mutability via RefCell.
Personally I use stringer[1] to handle all the string generation and then implement the valuer and scanner interfaces on that type. Boom transparent mapping between useful values and their corresponding db representation without having to write so much boilerplate.
type Book = {
id: number;
name: string;
genre: Genre;
};
type Genre =
| "Adventure"
| "Comic"
| "Crime"
| "Fiction"
| "Fantasy"
| "Historical"
| "Horror"
| "Magic"
| "Mystery"
| "Philosophical"
| "Political"
| "Romance"
| "Science"
| "Superhero"
| "Thriller"
| "Western"; const someBook: Book = {
id: 1,
name: "Title",
genre: "wstern"
// Compile error: [tsserver 2322] [E] Type '"westrn"' is not assignable to type 'Genre'.
};
That's not how string literals work in Typescript. If you mis-type the string you'll get a compile error. It won't make it to runtime.Mind. Blown.
My biggest typescript gripe is the fact that interface and type are _nearly_ interchangable, and many codebases just use interface wholemeal where it isn't really appropriate.
The type and interface is just because they are structural typing. It's attempting to stay faithful to JavaScript after all. Without that then the intuition breaks and not consistent.
Some people love reinventing the past.
"go generate" is really a red herring. It's completely meaningless. It allows you to define some commands that get run when you type "go generate", but... if I define a shell script called "blah", I can get some commands to run every time I type "blah". go generate doesn't do anything useful.
In Go i actually revert to the old C custom of adding a private length value at the end so i can iterate over all values.
Like so
type Color int
const (
Blue Color = iota
Green
Red
limit
)
for i := Blue; i < limit; i++ { ... }
Go really needs proper enums...I searched recently and most of what I saw were either in depth books about the language itself, outdated blog posts, or non-relevant books that just happened to use go to explore an unrelated topic.
To the parent post, there are several articles on Go Beyond[1] that walk through development of an open-source, real-world application called WTF Dial[2]. The source is available on GitHub and you can ask Go application design questions on the Discussions board[3].
I don't understand why you would ever want to possibly save space in a database at the cost of consuming it in your binaries instead. You're almost certain to deploy more copies of your binaries than you are of your database.
Plenty of problem spaces still wish to repeat the same value many times and give it a more human readable name when necessary and not coordinate a shared DB connection or even a dynamic string pool.
On the other hand, the efficiency concern it presents is real, and just repeating "sum types" is not, alone, enough to address it. Many languages with sum types would still store, and even more still serialize, a string.
If you are serializing this data a lot, then having ints vs strings is a significant advantage.
Again, it depends on your use case. If you don't care about serialization size, then I agree, it's extra effort that you may not need.
Even in this era of fast computers and preposterously large storage, one sometimes hits a situation where the way to get the improvements you need is to start number-representing your strings.
And yes, you may not start with ints, but you could easily add code for the marshal/unmarshal later on to convert those strings to ints for serialization purposes. And it wouldn't require a change to any of your other code, not to mention that if you stored these values in a database already you don't need to perform a migration either.
I will trade - unhappily - ADTs for value types, automatic memory management, some language-level concurrency support, a compiler that builds our largest project in under two minutes, and a community large enough I can spend my time training new hires on fundamentals and business problems and not tool onboarding.
A {
Field1: field1,
Field2, field2,
}
Now adding a new field to A would require ensuring that all code paths initialize Field3, otherwise you're going to have silent errors at runtime. This has been solved ages ago in Java and C# and similar languages by means of constructors.You are correct that every situation where the struct in Go is initialized "bare" would need to be addressed if a field is added, but Go considers this a feature, not a bug (and, conversely, considers "bare initialization" of structs at dozens of places in your code to be bad practice if that struct could ever grow new fields). If you're bare-initializing structs, you're comfortable using them in a "loosey-goosey" context where zero-initialized fields are permitted (or, better, useful... https://www.youtube.com/watch?v=PAAkCSZUG1c&t=6m25s). In Go, the issue of required structure is addressed by wrapping the struct in an interface and then providing a function in the package that can create an instance of the interface. Used in that way, you get something very similar to a Java class (though Go doesn't force you into the "everything is a class" paradigm that Java demands).
I see this dismissive philosophy in golang a lot (I'm not saying you're doing it, mind you). The entire language is full of arbitrariness. I've seen enums being dismissed by the golang team just because, without providing any meaningful arguments. Same with how nullability was not addressed in the language, contrary to how proper modern languages have tacked the issue. The excuse? "that's how the underlying machine operates". Quite meaningless and dismissive really.
Time and time again, it's been shown that the goal is to have a simplistic (not simple) language that also makes it easy to write the compiler for. This breaks down at larger scales because reality is complicated.
// pill.go
package painkiller
//go:generate stringer -type=Pill
type Pill int
const (
Placebo Pill = iota
Aspirin
Ibuprofen
Paracetamol
Acetaminophen = Paracetamol
)
Then running `go generate` will yield: $ cat pill_string.go
// Code generated by "stringer -type=Pill"; DO NOT EDIT.
package painkiller
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Placebo-0]
_ = x[Aspirin-1]
_ = x[Ibuprofen-2]
_ = x[Paracetamol-3]
}
const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"
var _Pill_index = [...]uint8{0, 7, 14, 23, 34}
func (i Pill) String() string {
if i < 0 || i >= Pill(len(_Pill_index)-1) {
return "Pill(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]
}
Note: indentation is messing up because of Hacker News, so ignore the indentation.Code generation is always the last resort.
Where I work we are a go house, and the number of tools I've seen in our pre-commit configurations and in our development environment setup scripts is pretty intense. So is the number of questions around said tooling. There's a lot more friction than I'd expect. I can't even use lack of experience as an excuse for these questions because they're really talented people. Some of them have worked on the product for years, and have literally moulded the product's tooling into what it is today.
Book
Genre
BookToGenre
GenreToGenre
https://www.progtools.org/article.php?name=oberon§ion=co...
Some links are broken now, because ETHZ no longer hosts the A2 site, however you can get the latest language report at http://cas.inf.ethz.ch/boards/2/topics/1
And the source code and old documents for the original A2 OS at github, https://github.com/metacore/A2OS
might be slower but it would have been more succinct to write and easier to read.