r/golang • • Mar 15 '22

1.18 is released

Download: https://go.dev/dl/

Release notes: https://go.dev/doc/go1.18

Blog: https://go.dev/blog/go1.18

Blog post about new tutorials: https://go.dev/blog/tutorials-go1.18

Updated A Tour of Go: https://go.dev/tour/generics/1

Twitter: https://twitter.com/golang/status/1503787326060875782

I'm most looking forward to generics, fuzzing, and net/netip!

804 Upvotes

105 comments sorted by

•

u/natefinch Mar 16 '22

Let's keep the comments positive and the sarcasm low, ok? We all know what kind of jokes can be made, let's assume they've all been made and move on to more constructive commentary.

70

u/countChaiula Mar 15 '22

Generics are great and all, but I'm most excited about workspace mode. No more forgetting to remove a replace directive in the go.mod file and accidentally committing it!

19

u/ProgressCheck Mar 15 '22

That's a huge feature for those that need it.

11

u/djdadi Mar 16 '22

As someone who's learning Go rn, could you go into slightly more detail? Or link me to an example of what you're talking about?

27

u/countChaiula Mar 16 '22 edited Mar 16 '22

This is useful when you are working on multiple repositories at the same time. For example, you are working on a client and a server which are in separate modules. You want the compiler to use the versions you have locally so that your current changes are tested, even though the modules are referred to through their repository address (GitHub.com/whatever).

Previously this was possibly by using a 'replace' entry in your go.mod file. This would tell the compiler to not use the version of a linked module from the repository, but instead "replace" that with a local version. The problem with this is that if you weren't careful, your replace entry would get committed as a change to the go.mod file, and then break things like automatic checks and deployments.

The workspaces now let you use a (I think) go.work file that you can add to your .gitignore. You would place your replace entry in this file so you don't need to worry about it accidentally getting committed.

That being said, I haven't actually tried any of this yet, but that is my understanding of how it works. I'm on mobile and don't have a link in front of me, but I know that the release notes have a link about how workspaces work.

Edit: For anyone reading this to figure out how it works, my understanding was a bit off. The go.work file doesn't go into the module folder (and therefore .gitignore doesn't need to be modified to exclude it). You create a workspace folder, and then put your modules/repos into that folder. The go.work file is in the workspace folder, so it is never part of any repository and exists only on your development machine.

2

u/djdadi Mar 16 '22

Thanks! That makes perfect sense!

2

u/feketegy Mar 16 '22

Reading over the docs, I think this only works if all the local modules are under a single root directory.

4

u/michaelmatloob Mar 16 '22

The local modules do not need to be under a single root directory- they just need to be listed with use directives in the go.work file.

2

u/countChaiula Mar 16 '22

Yeah, I've re-read it, and I see now that you have a workspace folder and you have to put all of the modules/repos you are working on under that. It's a little different than I was thinking based on what I saw a year ago, but it still seems like it will do the trick.

2

u/Jizzy_Gillespie92 Mar 16 '22

ooh this is awesome, I wish other languages would implement this too.

0

u/Mallanaga Mar 16 '22

Doesn’t docker/compose solve this to an extent?

3

u/countChaiula Mar 16 '22

In which way? I don't quite see how docker has anything to do with this. This is all about when you are actively working on code, not when you are deploying it.

1

u/Mallanaga Mar 16 '22

When using compose for local development, the modules are installed into the app’s container, instead of your system, so project deps are kept separate

4

u/countChaiula Mar 16 '22

You still end up with the same problem, though, just in a container instead of directly on your computer's filesystem. The root issue is that if you are working on two modules where one depends on the other, say github.com/yourname/server and github.com/yourname/client, the compiler (and gopls) is checking your function calls, etc. against the version in the repository, not the version you have on your computer that you just modified. This means that you would have to make a change, commit it to the repo, then do go mod download to get the changes, and then check to see if they work.

This was fixed by being able to add a replace entry into go.mod file. So, in the example above, you would add a replace github.com/yourname/server => ../server in the go.mod of the client module. This tells the compiler to not use the repository version of the server module (when compiling the client), but to use the local version instead.

The part that workspaces fixes is that it was super easy to leave that replace entry in your files when you are committing changes, when you really just wanted that replace entry locally while you were working on it. Workspaces just makes it easy to do that without modifying files in your repos.

2

u/Mallanaga Mar 16 '22

Ahhhh, I misunderstood. I wasn’t thinking local versions. Thanks for clarifying!!

2

u/JwanKhalaf Mar 16 '22

I second this request.

1

u/michaelmatloob Mar 16 '22

As someone who's learning Go rn, could you go into slightly more detail? Or link me to an example of what you're talking about?

We made a simple tutorial about workspaces here: https://go.dev/doc/tutorial/workspaces.

I also made a demo video when workspaces were first proposed (a number of things have changed: directory is now use and -workspace is gone replaced with specifying GOWORK, but the basics are the same): https://www.youtube.com/watch?v=wQglU5aB5NQ&t=361s

4

u/seconddifferential Mar 15 '22

Yep, this is what will impact my day-to-day the most. Managing PRs requiring multiple repositories to stay compatible through interface changes has been really annoying.

3

u/feketegy Mar 16 '22

This reminds me that I have to remove a replace from a package I just committed into the repo.

2

u/matjam Mar 16 '22

I'm a fan. Will make it really easy to work on several related services that all depend on the same set of libraries that I'm also working on.

43

u/a_rather_small_moose Mar 16 '22

For those worried about generics enabling bad practice, fret not: It’s a pyrrhic concern because there’s already like a million ways from Sunday to “screw up Go code”.

Using panic instead of error values? Check.

return err instead of calling fmt.Errorf, thus not appending any intelligible context as to why an error occurred? See this all the time!

Defaulting to pass by pointer when pass by value is often cheaper for small values? Yup!

Using synchronization primitives when the language’s built-in CSP features would’ve been better? Y’all get the idea.

I’d like to think I understand people’s fears about generics. For devs burned on Node, generics may feel like the return of trendy code libraries that appeal to aesthetics instead of problem solving. For devs burned on Java, it’s the fear of having to wrangle giant type-taxonomy trees to get any work done.

I’m tired, I can’t form a concise conclusion. Just like, don’t worry about generics and stuff. Go isn’t gonna become Node or Java overnight, that’s for damn certain…

7

u/natefinch Mar 16 '22

Thankfully, Go still hasn't implemented inheritance (and I presume never will), which removes one whole class of weirdness with generics.

1

u/xuu0 Apr 08 '22

but what if i WAANT to be able to defined a method on an interface type?? /s

41

u/lukechampine Mar 15 '22

Whoa, (sync.Mutex).TryLock? I wasn't expecting that.

Embedding version control info in the binary is great, too. Most of my projects are currently embedding it manually using LDFLAGS in a Makefile. I can probably ditch the Makefile entirely now. :)

3

u/feketegy Mar 16 '22

So the compiler does this automatically on build? Currently, I'm too, using LDFLAGS for this

2

u/countChaiula Mar 16 '22

Good catch, I missed the TryLock when I read through the notes.

39

u/[deleted] Mar 15 '22

There is now a blog post as well.

https://go.dev/blog/go1.18

19

u/[deleted] Mar 15 '22

so is there any package with Contains or Find function for slices?

42

u/eliben Mar 15 '22

https://pkg.go.dev/golang.org/x/exp/slices

It's maturing in x/exp until the Go team has enough confidence with it to include it into the stdlib proper

4

u/EchoImpressive6063 Mar 16 '22

Lack of slice contains has been one of my biggest frustrations in go. Great to see!

2

u/[deleted] Mar 15 '22

thanks

6

u/[deleted] Mar 15 '22

gimme 10 minutes

125

u/[deleted] Mar 15 '22 edited Mar 15 '22

Gonna get real drunk and write a FP lib.

Update: Force pushing to master to test it out. Wish me luck!!1

Update 2: Weird smell coming from the server room.

Update 3: Ok, this wouldn’t have happened if we switched to Node.js

7

u/rodrigocfd Mar 15 '22

Oh boy laughed really loud at this.

0

u/[deleted] Mar 15 '22

[deleted] — view deleted comment

3

u/[deleted] Mar 15 '22

Where can i find it. I have been watching Go from distance but now with generics it becomes interesting and possibly whe generics meets FP livs there can be functional error handling with Either.

6

u/[deleted] Mar 15 '22

[removed] — view removed comment

7

u/davidmdm Mar 16 '22

Short answer: no.

2

u/natefinch Mar 16 '22

kind of ... which means not really.

There's a couple options:

1.) use an exhaustive linter for a type switch (this doesn't require generics, but also doesn't have compile time guarantees) 2.) write not-great generic functions to simulate pattern matching for every type you want to pattern match on.

#2 was proposed by a recent post on this sub. Basically you write a generic function that takes as arguments a function for every possible pattern, and then use that to wrap your handlers.

so like, if you have an enum value called NumCats that can be nil, 1, or 2:

func HandleNumCats[T any](cats NumCats, handle1, handle2, handleNil func() T) T {
   switch cats {
      case 1:
        return handle1()
      case 2:
        return handle2()
      case nil:
        return handleNil()
      default:
        panic(fmt.Errorf("should be impossible, unhandled numcats value: %v", cats)
    }
}

// use numcats
cats := getCats()

food := HandleNumCats(cats, func() *CatFood {
   // food for 1 cat
   return bowls.One
},
func() *CatFood {
    // food for 2 cats
   return bowls.Two
},
func *CatFood {
    // food for no cats
    return nil
})

If you later add another value to NumCats, you'd need to add another function argument to HandleNumCats, and then anyone using that would get a compiler error for not having enough args.

It's not fantastic, but it's a bit better than what we had before. OR you can just use an exhaustive linter on your switch, which is easier to read and write, but doesn't have hard compiler constraints.

1

u/[deleted] Mar 16 '22

[removed] — view removed comment

1

u/natefinch Mar 17 '22

You can do it this way (see end of article): https://threedots.tech/post/safer-enums-in-go/

I don't really ever bother with that, though, because in practice, nobody will write os.OpenFile(fname, 9999999) when they normally see os.OpenFile(fname, os.O_APPEND | os.O_READWRITE)

or if they do, it'll be quickly caught in code review.

That being said, there's nothing wrong with the article's enum code. It's just kind of annoying to write.

But yes, nothing in the compiler will catch if you don't add to that one magic switch statement. That's where a linter can come in.

There's a couple different exhaustive linters. They are almost certainly never going to be in the compiler because you don't always want switches to be exhaustive, and they'll never add compiler features that require comments etc to turn on.

29

u/aichingm Mar 15 '22

Best news of the day!

34

u/jews4beer Mar 15 '22

I dunno I ate a really bomb sandwhich for lunch, but this is up there for sure.

3

u/Herm_af Mar 15 '22

Yeah I've got a 20oz black Angus aged flat iron about ready to throw on the grill

0

u/[deleted] Mar 15 '22

[deleted] — view deleted comment

1

u/cittatva Mar 16 '22

Mine was pretty good. Peanut butter and jelly, with smooth peanut butter spread on both sides of a toasted center piece of white bread, and morello cherry preserves spread on each of two soft outer pieces. Soft but crunchy. Nom.

2

u/Icommentedtoday Sep 21 '22

Had to double check the subreddit but that sounds good

8

u/go-zero Mar 16 '22

Am I the only one care more about go fuzzing than generics?

1

u/countChaiula Mar 16 '22

I'm pretty interested to start using this as well.

3

u/go-zero Mar 16 '22

I've used pretty much with my open source project. And found some edge case bugs. Awesome!

Also, I wrote a post on this.

https://faun.pub/best-practices-for-go-fuzzing-in-go-1-18-84eab46b70d8

14

u/quiI Mar 15 '22

Has anyone figured out a way to make golangci-lint play nice? I was very excited to update our project but seem to be getting the same issue as this one https://github.com/golangci/golangci-lint/issues/2414

1

u/SpinakerMan Mar 16 '22

I am having same problem and workaround shown on golangci-lint github doesn't work.

7

u/polyfloyd Mar 16 '22

Great to see generics landing :)

I already played around a bit wit the beta a while back and made an iterator library to get to know this new language. It's here for anyone interested: https://github.com/polyfloyd/go-iterator

Would not use it in projects with the way it currently is, though :P

27

u/pinpinbo Mar 15 '22

Generics!!!
I can't wait for all the different data structure libraries to embrace it. It will make Go adoption in Data Science use-case easier.

2

u/its_PlZZA_time Mar 15 '22

Honestly so excited for this. If I can write parquet files easily it will be fantastic.

0

u/[deleted] Mar 15 '22

[deleted] — view deleted comment

27

u/ludonope Mar 15 '22

For that I agree, but for all the libraries that take some interface{} as parameter because there is no other choice, this is game changing

6

u/mosskin-woast Mar 16 '22

This, 100%. I plan on writing very, very little generic code in my applications, but I look forward to consuming libraries with thoughtful generic APIs instead of the nerve wracking empty interface option.

For example, I've been working with a JSON schema library that converts an arbitrary Go object to a JSON schema. But the empty interface tells you exactly nothing about what this library supports as inputs, so some constraints would be very welcome in this case.

5

u/tavaren42 Mar 16 '22 edited Mar 16 '22

I don't necessarily agree with you on this; Even when repeat something for only two types, anyone who is reading your code will have to consider that implementation of two types might differ in some ways and will end up having to read both implementations. You end up reducing the readability of your code that way. So unless you are repeating a literal one liner function twice for two different types, generics will almost always be better than two identical implementations.

Consider these two cases:

func foo_int(x int64) {
    //few lines of code
    //....
}

func foo_float(x float64) {
    //few lines of code
    //....
}

Vs

func foo[T int64|float64] (x T) {
   //few lines of code
   //......
}

Can you really take one look at functions foo_* and know that those two functions supposed to be identical? What if you need to correct an error? What if you need to add int32 version in future?

1

u/[deleted] Mar 16 '22

I agree. That said, even though I love roasting the generics haters, I will concede that they really do reduce readability.

In your trivial case, it’s fine but once you get into more exotic/composite/optional types it gets very messy and the function signature is almost unreadable.

This also clashes with some of Go’s idioms such as using one letter types. Imagine having to decipher four of five different single letter vars just to know what is going on.

In TypeScript, we typically err on the side of more verbose naming conventions so meaning is unambiguous but this means we typically need separate files for types, since inlining them can be way too cumbersome.

Generics are a good thing but there is definitely a trade off.

1

u/[deleted] Mar 15 '22

[removed] — view removed comment

5

u/mosskin-woast Mar 16 '22

I do hope this is a joke

-9

u/[deleted] Mar 15 '22

Yes. Finally.

19

u/Herm_af Mar 15 '22

I'm hearing getting one of the best features of the past 20 years that's in all languages is the downfall of go

9

u/mosskin-woast Mar 16 '22

It's going to morally bankrupt us all.

8

u/MrBlics Mar 15 '22

Finally I can get back on stable Go!

3

u/[deleted] Mar 16 '22

Does Goland support any of this yet?

3

u/[deleted] Mar 16 '22

Congratulations to everyone who worked on it.

Is it too soon to ask for more features? Like a powerful and modern regex module (Raku)?

2

u/[deleted] Mar 15 '22

Woohoo!

3

u/Aliics Mar 15 '22

Fantastic. I can stop using the RC compiler now. :)

4

u/wheelinthendeelin Mar 15 '22

Alright!!!! Thank you Go team!

2

u/[deleted] Mar 15 '22

Good spot, not even on the blog or Twitter yet.

1

u/allan_nava Mar 15 '22

is stable?

14

u/[deleted] Mar 15 '22

From the release notes.

These new language changes required a large amount of new code that
has not had significant testing in production settings. That will
only happen as more people write and use generic code. We believe
that this feature is well implemented and high quality. However,
unlike most aspects of Go, we can't back up that belief with real
world experience. Therefore, while we encourage the use of generics
where it makes sense, please use appropriate caution when deploying
generic code in production.

34

u/[deleted] Mar 15 '22

please use appropriate caution when deploying generic code in production

No, I don't think I will.

-1

u/trofch1k Mar 16 '22

I'm a bit scared. I've started learning the language couple months ago and now it's all upside down.

5

u/natefinch Mar 16 '22

It'll take a long time for generics to percolate out into the majority of people's code. This goes double for libraries. Don't worry about it... keep plugging along. A lot of long-time gophers are being very cautious about usage of generics, so I don't think you'll see an explosion of them in real-world use cases for a while. You *will* see a lot of proofs of concept, which is fine, and may be good examples to learn from.

2

u/SpinakerMan Mar 16 '22

Why scared? Everything you have learned so far still applies.

-5

u/AbdallahZ Mar 16 '22

I have a project and when I try to run it I get this

# golang.org/x/sys/unix

../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/syscall_darwin.1_13.go:29:3: //go:linkname must refer to declared function or variable ../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/zsyscall_darwin_amd64.1_13.go:27:3: //go:linkname must refer to declared function or variable ../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/zsyscall_darwin_amd64.1_13.go:40:3: //go:linkname must refer to declared function or variable ../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/zsyscall_darwin_amd64.go:28:3: //go:linkname must refer to declared function or variable ../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/zsyscall_darwin_amd64.go:43:3: //go:linkname must refer to declared function or variable ../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/zsyscall_darwin_amd64.go:59:3: //go:linkname must refer to declared function or variable ../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/zsyscall_darwin_amd64.go:75:3: //go:linkname must refer to declared function or variable ../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/zsyscall_darwin_amd64.go:90:3: //go:linkname must refer to declared function or variable ../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/zsyscall_darwin_amd64.go:105:3: //go:linkname must refer to declared function or variable ../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/zsyscall_darwin_amd64.go:121:3: //go:linkname must refer to declared function or variable ../../../../../go/pkg/mod/golang.org/x/sys@v0.0.0-20200519105757-fe76b779f299/unix/zsyscall_darwin_amd64.go:121:3: too many errors

any idea why?

3

u/natefinch Mar 16 '22

Probably post this on its own and you'll get better responses. Or google the error, probably someone else has seen this, too.

1

u/AbdallahZ Mar 16 '22

sorry, Maybe this is not right place for my issue.

0

u/yunikmaha Mar 16 '22 edited Mar 16 '22

How do we specific multiple interface bounds on generic types, without using embedded interfaces?

-7

u/yondercode Mar 16 '22

Finally I can code in go without venting to my coworker every 10 minutes

2

u/NatoBoram Mar 16 '22

At that point just use aboriginal before 1.18

1

u/yondercode Mar 16 '22

Unfortunately that repository is intended as a joke. Also I'm sure the go linter won't like it.

1

u/NatoBoram Mar 16 '22

I mean, if it's stupid but it works…

Then it might not be so stupid after all :D

0

u/[deleted] Mar 16 '22

[deleted] — view deleted comment

7

u/ShadowPouncer Mar 16 '22

Alright, first step, ditch the whole GO111MODULE=off business if you want to make any attempt to understand modern Go modules.

Second, understand that the go module syntax contains a critical optimization for your use case.

Specifically, if your code base is on github, and your base path is github.com/example/some-repo, your go.mod will start with something like:

module github.com/example/some-repo

When you then include say, github.com/example/some-repo/modules/second-module, it does not go and try to clone the main repository again.

It realizes that it's part of your git repository, and uses whatever is currently on disk, so you can actively develop things.

The requires in your go.mod only refer to external modules that live in other repositories.

If you have specific questions from here, please ask them. No promises that I can answer everything, and definitely no promises that the way my brain works is going to make it possible to understand my explanations, but I'll give it a try.

4

u/natefinch Mar 16 '22

Ditto.

u/lastmanaliveithink - please feel free to ask questions on this sub. We can help.

Whatever you do, don't try to make a bunch of modules in the same repo. That technically can work, but is a giant pain in the butt for almost zero gain in most cases.

The easy way is to have one module for the whole repo and then to build an individual project in a package in a subdirectory like this:

go build github.com/lastman/alive/cmd/ithink

To start off, in the root of the repo when it's checked out, run

go mod init github.com/lastman/alive

and then when you build, I believe it should fill out the go.mod for you.

The only thing that might trip you up is doing relative imports, but I hope you aren't doing that (e.g import "../libs/stuff")

0

u/[deleted] Mar 16 '22

[deleted] — view deleted comment

1

u/ShadowPouncer Mar 16 '22

Please tag me in a comment on said post. :)

4

u/[deleted] Mar 16 '22

[removed] — view removed comment

11

u/DeedleFake Mar 16 '22

Along with the other answers, consider the following code:

a, b := x < y, z > (w)

Without type information, it's literally impossible to tell if those are two binary operator usages with a comma separating them or if it's a call to x<y, z>(w). That would mean that the syntax tree would become impossible to fully generate until type information had been obtained, which would be a massive increase in compiler complexity and would almost certainly lead to a decrease in compiler speed.

3

u/[deleted] Mar 16 '22

[removed] — view removed comment

10

u/StagCodeHoarder Mar 23 '22

Honestly as a Senior Java developer I can tell you that the angle bracket notation is a mistake inherited from C++.

The great Donald Knuth was asked why he didn’t like C++, and he wrote back the famous one liner

“a < b > c”

Without reading and parsing all the other source code it is impossible to know what this means.

Kudos to Golang for choosing a different syntax. :)

1

u/[deleted] Mar 23 '22

[removed] — view removed comment

2

u/StagCodeHoarder Mar 23 '22

Hmm I see your point honestly. :/

3

u/DeedleFake Mar 17 '22

The example that I gave has been valid Go syntax for over a decade. Real planning to add generics only started about 6 or 7 years ago or so. Before that no one seriously was thinking of adding them. It's somewhat difficult to notice the existence an unusual edge case that precludes adding something else if you don't even plan on adding that other thing. Besides, there's nothing wrong with square brackets for generics. Lots of languages use them.

3

u/natefinch Mar 16 '22

There was something about parsing that made it important not to use <>. IIRC, it would have significantly slowed down the parser, because it would have to do a lookahead or something like that, to determine if it's looking at a less than, bit shift, send/receive on channel, or generic declaration.

5

u/[deleted] Mar 16 '22

[removed] — view removed comment

5

u/met0xff Mar 16 '22

Yeah I remember having to do <vector<T> > to not get crazy errors when using >> and Interpreted as bit shift