Go - one language you should try
This is a modal window.
The media could not be loaded, either because the server or network failed or because the format is not supported.
Formal Metadata
Title |
| |
Title of Series | ||
Number of Parts | 96 | |
Author | ||
License | CC Attribution - NonCommercial - ShareAlike 3.0 Unported: You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this | |
Identifiers | 10.5446/51719 (DOI) | |
Publisher | ||
Release Date | ||
Language |
Content Metadata
Subject Area | ||
Genre | ||
Abstract |
|
00:00
Group actionData managementWordSoftware testingKey (cryptography)SoftwareSign (mathematics)Workstation <Musikinstrument>Formal languagePower (physics)Multiplication signProcess (computing)Projective planeSoftware engineeringLevel (video gaming)Computer scienceGenderBitCompilation albumSoftware developerUltraviolet photoelectron spectroscopyOpen sourceSystem callExtreme programmingGoogolAxiom of choiceDatabaseMilitary baseVideo gameGraphic designCycle (graph theory)Java appletShooting method2 (number)WeightHost Identity ProtocolSoftware bugChainCodeInternetworkingComputer animation
05:41
Point cloudSoftwareCodeBitAxiom of choiceCartesian coordinate systemCurveSoftware developerPoint (geometry)Projective planeOpen sourceText editorLine (geometry)AreaVirtual machineJava appletDomain nameAddress spaceOverhead (computing)Web 2.0Distribution (mathematics)Formal languageMultiplication signType theoryInheritance (object-oriented programming)Product (business)Parameter (computer programming)RoutingRouter (computing)ChainFront and back endsLevel (video gaming)Link (knot theory)Arithmetic meanGoogolPersonal digital assistantPressurePhysical systemRange (statistics)SpacetimeInformation technology consultingDot productSocial classGoodness of fitService (economics)Image resolutionEccentricity (mathematics)Electronic mailing listProcess (computing)Interface (computing)Binary codeComputer animation
11:22
NamespaceDeclarative programmingFunctional (mathematics)CASE <Informatik>Computer animationSource code
12:07
IcosahedronFormal languageFunctional (mathematics)Similarity (geometry)Cartesian coordinate systemPoint (geometry)Source codeDifferent (Kate Ryan album)Data structureProjective planeNumberElectronic program guideDirectory serviceDefault (computer science)SoftwareCoefficient of determinationComputer animation
13:43
Run time (program lifecycle phase)Run time (program lifecycle phase)Point (geometry)Data managementLink (knot theory)Library (computing)Virtual machineSoftwareOperator (mathematics)NumberPRINCE2Message passingBitServer (computing)Computer animation
15:04
ChainChainBitCompilation albumCompilerProcess (computing)CodeCache (computing)Enterprise architectureSource codeSoftware testingComputer programmingMultilaterationSoftwareSymbol tableLetterpress printingType theoryFerry CorstenRevision controlInternetworkingFormal languageCuboidFile formatOnline helpComputer animationSource code
17:03
File formatAliasingString (computer science)Initial value problemKey (cryptography)Dot productLevel (video gaming)SpacetimeComputing platformFormal languageLine (geometry)Context awarenessQuicksortSource codeJava appletParameter (computer programming)Term (mathematics)Reading (process)BitControl flowProjective planeLengthComputer architectureInstance (computer science)Type theorySocial classVariable (mathematics)Sign (mathematics)Interface (computing)CompilerMultiplication signSoftwareMappingFile formatComputer programmingMoment (mathematics)String (computer science)Electronic mailing listGroup actionMathematicsObject (grammar)DataflowField (computer science)Different (Kate Ryan album)Data structureBuildingSoftware industryInsertion lossProcess (computing)Functional (mathematics)Shape (magazine)AuthorizationFigurate numberPOKESingle-precision floating-point formatInterior (topology)Boolean algebraDefault (computer science)Constructor (object-oriented programming)Computer animation
23:03
RectangleStrutAreaInterface (computing)Square numberBroadcast programmingException handlingType theoryElectronic signatureParameter (computer programming)AuthorizationComputer programmingForcing (mathematics)Form (programming)DataflowInterface (computing)Square numberFormal languageLevel (video gaming)Social classFunctional (mathematics)Sheaf (mathematics)Server (computing)HierarchySoftwareAreaOrder (biology)Casting (performing arts)Dot productJava appletMultiplication signMetreVideo gameLibrary (computing)Sampling (statistics)Connected spaceElectronic mailing listProtein foldingComplex (psychology)Graph coloringBitEmailPower (physics)Set (mathematics)CodeExtension (kinesiology)Domain nameGoodness of fitHash functionTracing (software)Stack (abstract data type)Error messageSpeech synthesisObject (grammar)Pointer (computer programming)Computer animation
29:03
Server (computing)Form (programming)Source codeComputer animation
30:21
SoftwareCodeStructural loadContext awarenessMilitary baseVariable (mathematics)Source codeCognitionMultiplication signUsabilityRoundness (object)Reading (process)Entropie <Informationstheorie>Server (computing)Goodness of fitStatement (computer science)MereologyGoogolSource codeComputer animation
32:02
CoroutineThread (computing)Run time (program lifecycle phase)CSPRead-only memoryFlip-flop (electronics)Run time (program lifecycle phase)CoroutineThread (computing)DataflowConnectivity (graph theory)Cartesian coordinate systemIntegrated development environmentFunctional (mathematics)TelecommunicationWritingDifferent (Kate Ryan album)BitIntegerOcean currentRight angleSemiconductor memoryComputer hardwareCodeFormal languageNormal (geometry)NumberLogic gateSequenceSynchronizationConcurrency (computer science)Variable (mathematics)Order (biology)Reading (process)Parameter (computer programming)Type theoryLine (geometry)ImplementationInjektivitätFlip-flop (electronics)BefehlsprozessorComputer scienceServer (computing)Coordinate systemTypprüfungConnected spaceOperating systemCASE <Informatik>ExplosionClique-widthCore dumpArrow of timeDefault (computer science)MappingFlow separationBuffer solutionSystem callMultiplication signMessage passingHoare logicArithmetic progressionLie groupRobotWeb crawlerService (economics)Roundness (object)Operator (mathematics)Fiber bundleMultiplicationConstructor (object-oriented programming)Process (computing)Configuration spaceComplex (psychology)Reduction of orderFreewareMereologySoftwareComputer animation
40:52
Flip-flop (electronics)Function (mathematics)String (computer science)Service (economics)SynchronizationElement (mathematics)Maxima and minimaRange (statistics)Multiplication signCodeRun time (program lifecycle phase)Service (economics)DatabaseConnected spaceVideo gameElectric generatorMultiplicationSoftwareTouchscreenResolvent formalismNumberVirtual machineExpressionSource codeFerry CorstenCuboidPhysical systemDeclarative programmingSemiconductor memoryLatent heatSynchronizationElement (mathematics)Statement (computer science)Gene clusterDifferent (Kate Ryan album)Directory serviceElectronic program guideQueue (abstract data type)Binary fileBuffer solutionInstallable File SystemCASE <Informatik>Formal languageEndliche ModelltheorieRange (statistics)Cartesian coordinate systemDefault (computer science)Atomic numberReading (process)ProgrammschleifeCoroutinePoint (geometry)Computer architectureFiber bundleSingle-precision floating-point formatOperator (mathematics)Interface (computing)Programming languageProgram slicingFitness functionComputer fileView (database)Line (geometry)SequenceFluid staticsRevision controlFault-tolerant systemConstructor (object-oriented programming)Computer programmingInternetworkingJava appletAeroelasticityData centerCausalityDirected graphGraph coloringUniqueness quantificationWindowSuite (music)System callBit rateRoundness (object)DialectFunctional (mathematics)INTEGRALComputer animation
49:42
StrutString (computer science)Meta elementPortable communications deviceCodeStudent's t-testIntegrated development environmentKeyboard shortcutGoodness of fitSource codeType theoryMultiplication signFormal languageCASE <Informatik>INTEGRALForm (programming)Software bugAxiom of choiceStructural loadHand fanInsertion lossFreewareGoogolEntropie <Informationstheorie>Software testingProcess (computing)Data conversionPhysical systemData structureComplex (psychology)WebsiteForcing (mathematics)Open sourceMereologySoftwareInformationLibrary (computing)Error messagePressureWaveRevision controlWeb browserVisualization (computer graphics)Coroutine2 (number)Bookmark (World Wide Web)Intrusion detection systemMathematicsFile formatIntegerCovering spaceCartesian coordinate systemLinear regressionFehlererkennungText editorAuthorizationPairwise comparisonBitComputer animationSource code
56:39
Virtual machineVoting
Transcript: English(auto-generated)
00:04
I think it should be working, so hello, and welcome to my session about a language called Go. I'm really happy to see you. I think, well, I hope the coffee is good. I've had just one so far. Who here is enjoying NDC for their first time?
00:22
Me as well. It's my first time at NDC in Oslo. It's my, well, second time in Oslo because I have a friend living here, so it's amazing to be here. It's a lovely city. Well, the weather is very generous to me as well, again, which is also amazing. And this talk is about a funny language called Go funny, as in it brings fun. It's nothing to be joked about because you can do very serious things with it.
00:44
If you have any questions, of course, well, you know, try to raise your hands. I'll try to notice you, and I'll try to repeat the question that you have and maybe even answer. So starting with a bit about myself. Well, you could describe me as a Java developer in a .NET, primarily in a .NET conference,
01:01
talking about totally non .NET and not JVM language. A bit out of place, but, well, to give myself a bit of a background, I come from Krakow in Poland. I now live in London. I run a conference called Geekon, also have been involved in the community as in running the Polish Java user group, doing, well, founded Krakow Hadoop user group,
01:22
which now is called DataKrakow because, well, data science is much more popular. Apart from, well, interested in all the usual software engineering things that you would expect, one thing that needs to be mentioned is Software Craftsmanship Krakow. It's a group which you would expect to be about testing and software craftsmanship,
01:41
and we founded that in 2010. It's actually a group in which we read computer science papers. So every two weeks, we pick a paper, well, people read it before, and then we come and meet and discuss it for, give or take, two hours. So it's a very, well, different thing to what people usually connect with with software craftsmanship,
02:03
but I think it's worth to be noted because we've had over a hundred meetups so far. Anyway, me, trying to describe myself in a single sentence is a developer going deeper, so if something works, I'm usually suspicious. Why is it working? This shouldn't be like that.
02:21
It shouldn't compile, which means I like to go deeper and deeper and deeper and deeper, well, with all of the time that it requires. One disclaimer, my opinions are my own. You can find it on LinkedIn, who do I work for, but this talk is not connected to my employer in any way, of course, because they are very brand protective, which means they don't want me to mention their name.
02:44
That's their choice. If you have any questions, shoot or try to find me after the talk. If you have any questions during the talk and you would like to raise your hand, I would love to answer. So, Golang. It's a free and open source language.
03:01
As in free beer, you can download it from the internet and use it, and you don't have, as of now at least, I haven't heard that, you don't have to worry about a large database company suing you for using that. So, it's open source, so again, you don't have to worry. I haven't seen a legal department that would give people problems
03:21
because of their attempts to use Go. It's BSD license, so that should be okay in most places. Of course, there might be some extremes. I'm not a lawyer. It comes from Google, so it has been invented. Google uses it. At least that's what they say, because they've never worked for Google,
03:40
so I have no idea what does it look like internally. But it comes from there to solve a couple of problems. Who here has written some C or C++ in their lives? Yeah, there are some, let's call them inefficiencies, or problems, or minds, or well, 10,000 ways to shoot yourself in the foot very effectively,
04:00
blowing the whole leg and half your hip off in those languages. Go is nice, as in it allows you to save yourself from some of the problems. It takes some of the power away, and at first I thought that it's very limiting. That was going to be my first attempt. It feels like I can't do all the things that I used to be able to. Am I really going to be able to be productive in this language?
04:22
Then it turned out I'm not really missing all those features that much because I can still get the job done, and usually there are less bugs and there's less code. Go is fast, as in the whole... One of the key goals in creating that language has been speed.
04:41
Speed in compilation. You might have seen compilation processes for large C code bases that can take a day or at least a couple of hours. Go, I haven't seen really long Go compile times. Go compiles really, really fast. The whole tool chain is very fast, which means you can have very rapid development cycles,
05:03
which means you get feedback often. You can run your tests. You don't have to wait a day for a software deployment manager and their team to try to attempt to configure the thing and run CMake, DMake, your flavor of Make and wait for it to happen. Go has a mascot.
05:21
As every single, well, self-worthy open source project, it needs some graphic designers to help it. So for Go, Gopher is the mascot. And if you're already sleepy or thinking about lunch or some of the awesome stuff that you can see in the exhibition hall, I really love the VR experience there.
05:42
It's a bit of a mix-up between C++ and Ruby because of the syntax, because of the power and because of how low level Go gets. So if you're already asleep or getting there, play with it tonight. I really encourage you to. It's super easy to start with. You just need to download the tool chain and then you can start.
06:01
You don't need to download a specific operating system, a specific IDE, a specific something. Just the Go distribution for your machine of choice and a text editor and you're good to go. So, well, I always get questions about who uses Go. What companies use Go? Can I use some big brands to encourage my place to use it?
06:26
Well, Google, obviously, are the inventors of the language. Well, eBay, that might be a good thing. For some of you, it might be a bad. Dropbox, well, Bitbucket, now Atlassian, I think. Government UK, so that's a government entity. They use Go, the language.
06:41
And the great thing about UKGov is that some of their Go usage is open source. And I can only say some because I don't know of all of their Go usage, but government UK open source is a lot of their currently written software, which means you can actually, this is good enough for the UK government. This is the link to GitHub.
07:01
Have a look. It's serious stuff running on Go used by a government. That's a very good political argument for some of the discussions. Docker, of course, some other things. The wiki, that address has a much longer list of users. There is a lot of companies in London which use Go and experiment with Go.
07:22
I can give you a short story about a company that just happens to be in my area called Not on the High Street. I went, I think, a year ago to do a talk about Go, the language, because some developers were curious. And just a week ago, I learned that I've already started using that in production. That was nice.
07:42
To fill that story completely, how did I learn about Go? Well, I heard that Google has open sourced created this language, and I was just curious to start. I couldn't find a reason. And then we were doing, effectively, a router, an HTTP router in Java,
08:01
which means if you're doing any software in Java, it tends to grow into thousands of lines. So our software had, I think, well, ten thousands of lines, plus a couple hundred of XML lines, plus, of course, you had to use Tonkad and other things. And at one point in time, I thought, maybe we should take a step back. Maybe something is a bit wrong in here, because the amount of dependencies, the amount of things or crap
08:22
that you need to install to get it to essentially route HTTP requests and serve very simple things, it feels a bit too high. So we rewrote that into Go, and we ended up with around one-eighth of the code. And we got a single binary, and that was it.
08:41
And that felt really awkward, because, well, at least me coming from Java ecosystem, I'm used to bloated software, sometimes in verbosity. And then, in this language, well, this is everything. So we've shown it to other people. Well, okay, show me the code. Oh, that's readable. That looks like Ruby. I don't really understand all of the tiny details,
09:03
but those are details. Where is the rest of it? No, no, no, that's all. That is impossible. Because, as I said, it was around one-eighth of the code, and that was our first, well, serious project that we did for eBay in 2013. In Go, the language. And that's, well, then we started, well, having Go
09:22
as a regular piece in our toolchain. I do not encourage you to rewrite all your software into Go. That's never the solution. It's a great language for some usages. Well, for some uses, it's not perfect for everything, because I still believe there is no silver bullet, which obviously translates into I'm an engineer, not a consultant,
09:42
because then I will try to sell you mine. Where do I use it? All kinds of network-related middleware, yes. All kinds of, anything that needs to deal with sockets, with HTTP traffic, analyzed route, do something with that.
10:01
Go is super pleasant to use it, to use that. I know that there is a lot of companies that use Go for microservices. That wouldn't have been my first choice, because I personally prefer languages with a richer type system, because then you can reuse the domain language that you create in one application in the other,
10:21
which means I would probably tend to favor Scala right now. But there is a lot of Go usage in microservices space, and people are very happy with that, because the applications in Go, you can create them quickly, and you can run them quickly, and they usually behave quite well, which means a lot of the overhead that I mentioned, you don't have to go through.
10:41
And I mentioned Scala, because I like Scala the language. At first it hurts, because the learning curve is quite steep. Go has a much nicer, much more approachable learning curve. Just to answer the question that usually happens. Where not? Well, user interfaces, web applications,
11:02
well, you can't write them in Go. I haven't seen a Go to JavaScript transpiler just yet. It doesn't mean that there doesn't exist one. It's only that I haven't seen it. It's a back-end development language. It's really good there. But I've been talking for a couple of minutes now,
11:21
and I think it's time for, well, we have to go through some code. So, mandatory hello world, because of course we have to. Let's make it even larger. Yay. So, you have, well, a package declaration. That's obvious what it does.
11:41
We import fmt, so we import a namespace of another package that we will be using a function from. And then we have, well, we use a function from that. You can notice that it starts with an uppercase. That's a convention in Go. Anything that you want to export within a package,
12:04
well, has to start with an uppercase. Let's try to run it. So, go build main. That's done, and go run main. Oh, sorry. Yay. That was fast.
12:21
So, why is main not uppercase? Because main, that's a really good question. That's a catchy I. Main is this one special thing that you start your applications with. If you notice any similarity with a usual main function that's prevalent, that's present in many, many other languages,
12:42
that's exactly good. Your intuition guides you well. Main is this one special package in your source tree that is supposed to contain the entry point for your application. So, if we look at the directory structure here, well, there is bin, there is pkg, there is src.
13:02
Under src, well, you can have different packages there, and if you have any dependencies, they will end up here, but I'll talk about it later. If you want to create an application, the default would be that it will sit in a package called main,
13:21
and all of the other stuff should be your dependencies. So, if you want to have a number of applications, well, you will have a number of projects with different main directories, and all of the other things will be your dependencies, which encourages you to externalize and think about how you structure your software.
13:40
So, just a convention. So, we've seen a hello world. Why do I like Go? Coming back to that point, well, no runtime dependencies. What do I mean by that? I mean that I get...
14:09
So, this main, this binary, has everything that's needed. It only prints a hello world, and somebody could say that it's a bit large, that it takes two megabytes to just print, well, almost nothing.
14:23
Just say hello ndc, this very important message, but then it takes two megabytes. The answer is Go links everything statically, so you can take the binary, you can deploy it to all of your servers, and you don't have to worry about missing dependencies. Everything is contained there, which means your release management becomes trivial,
14:41
because you just need to, well, take a binary and deploy it to a number of machines. Your dependency, your library management becomes super easy, super pleasant. Your operations people will most probably be very satisfied with such an approach, because that gives you simplicity, and simplicity is what I really like in software.
15:05
So, deployment, as we said, super easy, much more pleasant than C, because we don't have to produce a lot of the artifacts that we would sometimes have to worry, cache for the compiler to optimize our enterprise compilation process.
15:23
And you've seen that I've compiled this tiny amount of code using a Go command, and I mentioned something called the Go toolchain, and now let's talk about the toolchain. Let's give it a bit of a look. So, if I type Go, I will see that Go is a tool for managing Go source code.
15:44
Yay. The commands are, so the built-in commands, the things that are built into the basic toolchain, the thing that you download from the internet, so anybody using Go, the language, anybody being able to compile, you can safely assume they can build. They can show documentation for package or symbols.
16:03
They can format and run a formatter. You can also generate, you can install dependencies, you can download dependencies, you can list packages, you can run, you can test, you can print your current version, because obviously you'll need to do that.
16:21
Being able to manage dependencies, being able to run your tests out of the box, that's usually a pretty good start. No other things are necessary. That's all built in. To be fair, what do tests look like? Well, tests are just simple programs that are supposed to have an exit code of zero as in any decent software, piece of software.
16:45
Well, that's a convention that they follow. But then they already give you something that you can test your code with, you can build, and you can manage dependencies, which means you can specify dependencies that sit, for example, on GitHub, and this tool can download.
17:02
And we'll see that a bit later. So, the Go command, we've seen that in action. And I mentioned Go format. Authors of Go decided that there are certain discussions in the software industry not really worth having in most of the context. One of them is formatting.
17:20
So in terms of Go, tabs versus spaces doesn't exist. I know it's a great flamer for having a beer over, but with the Go language you are supposed to be using tabs, and all break lines or all new lines characters will be converted into semicolons so you don't have to use them. So the way you place your returns actually matters.
17:43
That also means that every single piece of Go software should look the same. It's highly encouraged to run Go formatter after every save in your editor, and it's a very easy thing to configure. That also means that analyzing software becomes a much easier job
18:03
because you can make certain assumptions about what does the source code look like, how is it shaped, because everybody's source is shaped the same. And that also means that when you're reading somebody else's Go, why is this curly brace sitting in a new line and there is a comment in between? No, no, no. There is one way to do that, and everybody follows that.
18:26
This is more or less what it is. I'm saying more or less because how Keynote decided to format my text, it's a different story. But another great thing that I like about Go
18:40
is that it's very explicit about the types it uses. This is not supposed to give you an introduction. How do I start with Go, with absolutely everything, because I assume you are very intelligent people. You can follow the tutorials online on your own. I wanted to tell you why do I find Go as a very good and very pleasant language
19:02
and what features actually make me still like coding in it. After three years, I did the first proper commercial project in it. The types have their size in it, so you don't have to worry or wonder how many bytes does an int take. No, that's in the name. Is it assigned? Is it an unsigned? That's in the name.
19:24
What is it? No, it's all built in. For those of you who still program in C, that might not be a problem, but for people, for example, coming from Java or some other languages, that's a problem. If there is an architecture change happening in between or you're programming to a different set of devices,
19:41
well, an int32 is always an int32. This is what it is. This is how wide it is. You don't have to worry whether the default for that platform is 16, 14, 32, or something else. That problem is solved, which means your interfaces, especially for something that deals with bytes and some really low-level funny bits,
20:01
are very explicit, are easy to follow, and are easy to understand. A bit of syntax. Well, you can declare a variable and you can assign to it, or you can declare and assign at the same time, and you don't have to specify types sometimes because Go compiler can infer that. Well, another poke at Java, which still can't figure out what type of things,
20:25
even though it knows very well. And if you want to print a length of string, you call a function len with the arguments of the string that you want the length of, which means string is, unlike in some other languages,
20:43
string is not an object here or a class. It won't have methods like you would expect it to, which is just the way they decided to. It has some other consequences, but we'll see them in a moment. And now, let's have a look at maps, because maps here have quite a nice feature, which we'll see in a moment.
21:06
So, I declare a map, which is a map of from string to bool, nothing fancy, I initialize it with two values, and then I try to, in this very line, I try to access a key that's not set in there.
21:22
And instead of getting a null, like some languages would give you, you get false. And false is a zero value for boolean. So there is a concept of zero values or default values, what is the initial value of a variable, if you didn't bother or you didn't declare it.
21:42
That means that all variables, unless declared otherwise, you know what to expect for ints, that would be zero, for floats, that would be zero, for strings, that would be an empty string, for larger structs, that would be a nil. But it also gives you this tiny little perk,
22:01
that if you want to access a key inside the map, you don't have to check, like so many times we have, whether it exists in the map, and then if it doesn't insert it and then set it to a value. No, you can assume it exists and then operate it as if. Which means if you want to have a map with counters, you can just say map of the key and just increment it.
22:25
Because Go will make sure that if it wasn't there and you access that, that's a zero, you don't need to store that. But if you actually change that, sure, it will be there, stored as one, as you would expect. Which saves you a lot of lines across many, many projects.
22:41
Of course, I know it's a tiny detail, but it's really helpful. And then structs, because Go uses structs, it doesn't have classes which have, like Java, like Scala, like probably C Sharp classes, they decided to go with structs, as in the constructs that are just a list of fields.
23:01
And you can initialize them this way. So just pass the arguments or you can use named arguments and then the order doesn't matter. For a lot of reasons, having named arguments is really helpful because it just helps readability, especially in the public sections of your APIs.
23:21
And then you can call methods. Well, you can cast a variable to an interface and then you can call methods, but let's see interfaces. So we have a type that is called square that has just one variable inside called side.
23:43
And we declared that there is a function that operates on squares that's called area. And it will return an in32, which, well, the area for that is quite obvious how it works. So we define a square and we can call area on the square.
24:05
And now the question would become, why? How is it that it works that way? Well, so the authors of Go decided
24:27
that knowing how other people are going to use your code and having them to explicitly be able to say that import or extents or everything is a bit of a nuisance.
24:44
Maybe not a nuisance, but it's tiring and it brings complexity into the world. And you, by definition, cannot foresee all of the usages, all of the possible usages of your types. So instead of restricting and formalizing and maybe putting your type hierarchy into concrete,
25:03
you get structural typing. So if your class has methods that match a type that somebody else declared, it means your class fulfills some other type, which means if there is, I don't know, a Martian square
25:21
that somebody has designed that just meets the square method, I can cast, well, me or they can cast my square into their square because the methods match, and that's it. That seems really awkward at first because how is it going to work? But then it turns out to be an extremely powerful feature of Go the language
25:41
because it means that you get to use IO, you get to use a lot of the libraries that the authors couldn't have foreseen, what they can be used for. Just because the types match, you can cast and then you can use them in your program. And that's a really, really nice feature.
26:02
So where is it useful? As I said, IO, yes. All of your domain class hierarchies. If your domain class has one function, another function, another function, and that set of functions forms an interface,
26:20
it means you can use that type as something specific, which means if your domain class hierarchies are getting larger and larger and somebody wants to use it in a very peculiar or specific way, they usually can and they don't have to cast. Well, they do have to cast it, but they don't have to introduce special marker interfaces
26:42
into the whole type hierarchies, which for languages like Java, Scala, anything else, leads to, well, that forces an ugly, less and less specific, more and more generic hierarchy. So if you ever looked at what a particular array list
27:03
or a particular hash map looks like, what types those extend, in Go you don't have to worry about that because it's only about the methods that you declare. If the signature fits and if the list of methods fits another interface, well, you can use one type as the other and that's it.
27:22
That's helpful. And now let's look at some network programming because, well, the person speaking here previously has talked about network and using network quite a lot. So let's have a look at an echo server. Well, this is how much code you need for an echo server. Of course it's a sample, so it will be shared by definition.
27:44
Well, but this is it. You expose a listener address, you create a TCP listener, you accept connection, and then, well, this is just a server that will copy whatever you sent to it and then reply with the same. Quite silly, but, well, just to show you how much code is needed.
28:04
Because also it shows you another feature of Go, the language. You can see that when I try to listen, I get a channel and I get a second thing that's ERR. So the ERR thing is the error. If ERR is nil, that means that nothing bad happened.
28:24
But if ERR wasn't nil, that means that something wrong happened and I can examine. It's not a... nil will be the object that describes the unexpected situation. There is no exception. It's not that the flow of your program will be seriously altered.
28:41
Something will explode here and then you have an exception, couple of stack traces below or to the left, because why not? No, it's right in the same place because metals can return multiple things at the same time. So a TCP server, yay, good. So maybe we should actually give it a try
29:04
because there is something peculiar about that server that I want you to have a look at.
29:41
Let's try to print. Now we have an echo server running on port 4000, so we'll just... that's what is expected.
30:14
So you already see the problem. It's not really concurrent.
30:20
So, well, how can we make it concurrent? Well, first by removing the format, we will build it all. And now you see something about Go and its approach to coding.
30:41
You cannot have... this way. So I import it and I haven't used package called fmt. Go is extremely strict about leaving and letting you have unused variables or imports in your code.
31:02
It doesn't allow them, just that. Which means if you're debugging, playing with printable statements, because that's still my most frequent way of debugging simple things, it will be a bit painful.
31:20
But if you, in the large code bases that you usually work with, how much of the source code is left unused? I don't know, but there is probably some. Go will try to eradicate and get rid of every single thing that it can safely say that hasn't been... and is not accessible in any way.
31:42
Which is a really, really useful feature if you think about that in the context of, well, it's done at Google, which means the amount of software written there is huge, which means you want to decrease... you want to remove all of the cognitive load that's needed to read the software that nobody ever actually runs. Because why would you waste your time on that?
32:02
But we talked about an echo server. Well, that's... so does the concurrent one? Does the normal one? Does the concurrent one? Does the normal one? Well, for people who didn't notice that, I just added this Go line here.
32:24
What happens? What does the Go line... What does the Go instruction do? This way, without the Go instruction, I'm just calling a function called copy.
32:40
Like you would, nothing magical happens. Single-threaded, no concurrency whatsoever. Whereas when I have Go, I actually run it in a Go routine. So I make that function be called concurrently, and then this flow can continue.
33:01
And where that will happen is something that Go's runtime will manage. So Go routines, lightweight threads. When you spawn them, the idea is that you can spawn as many Go routines as you want as in they are extremely light, their stack will be light, there is no one-to-one mapping between a Go routine
33:21
and an operating system thread. So you don't have to worry that if you start anything more than, I don't know, eight on a desktop, only eight will make sense. No, this is not how you are supposed to think about that because Go routines are how you structure your software, and that's quite orthogonal to how your hardware,
33:42
your underlying hardware is going to run it. And you shouldn't have to worry about the hardware for most of the cases because in most cases you are there to solve a problem, which means express it with code and be able to run it. Go runtime will take care of that. That's, again, a normal function call
34:00
without the Go instruction, and that's running it in a separate Go routine. First question that comes to mind, well, how many threads will run? That's something that actually bit me and bit us at eBay at the very beginning of our history of Go.
34:22
There is an environment variable called gomaxprox, or there is a runtime parameter that you can observe and react to and change, which tells you how many concurrent Go routines can operate. It's usually useful to set it to something like your current number of hardware CPUs or cores
34:44
because anything higher will have the obvious problems. But that's something worth mentioning because it's biting so many people, and it has, and it will, because by default this value is set to one, which means only one can run at a time. So we can spawn functions
35:02
that will operate on a different thread. Awesome, how do you make them talk together? Because that's only, well, this is the necessary component. The answer to that is channels. Channels as a concept come from a very important paper called CSP or Communicating Sequential Processes by Mr. Hoare.
35:21
I would think that some of you at least have heard. If you have some spare time, if you would like to talk computer science with your friends, try to read this paper, try to discuss it, go through it because it's a really awesome paper. It's so much different to some of the concepts that we primarily use in most languages popular right now.
35:44
And in currently, in current world that's going more and more multi-core, multi-processes, multi-threaded, it makes things easier. And by making things easier, it reduces complexity. So we don't have to worry about how things are orchestrated.
36:01
Runtime will support that. You only have to make your implementation look nice. So Go uses a concept called channels. Channels are bits of memory. They are used to communicate between Go routines. They have types. So you don't have to worry about what comes in or what comes out. Type safety is there. And with type safety, because we talked about types,
36:22
we know what they look like in memory because we know the width. We know exactly what they look like. We also can push other data into those channels from different applications if we agree on the byte order. And channels are also thread safe. So you don't have to do manual synchronization
36:41
around using channels because channels will, under the hood, provide you with thread safety. You don't have to worry about explosions. You make a channel by, well, this instruction. You make a channel of a variable. Then we have a channel.
37:01
There are two types of channels in Go. One type is called buffered. The other one is called, one is buffered, one is unbuffered. Unbuffered channels, so channels that don't have a buffer, which means, well, they are unspecified in their size.
37:20
They are synchronous, and they will wait when you try to read from an empty one. Basic syntax, well, you've seen how you make a channel, you push things into a channel with this funny arrow operator, or you read from a channel, and you can assign it to a variable, and you can also get this extra variable
37:41
whether something was actually there. Because if you were reading from an empty channel, you will get the zero variable, just as I described it with maps. But if you'd like to have a distinction whether the zero that you read was because the channel was empty or because
38:00
that's actually what was in the channel, you can use that extra variable there. Some bits of code. You, of course, have to pass channel as an argument to a function because, well, it has to be able to communicate. This simple piece of code,
38:21
well, this piece of code will just put a random integer into the channel, and then another function will read it, and then it will reply with, well, received something. Absolutely trivial, nothing fancy in here. Just the basics so that you know more or less how it works. And as I said, that's not cool yet.
38:42
The cool thing about channels, apart from, well, passing variables and passing data all the time, is that you can use them to coordinate. And you can, well, what you can do is make a channel and then have a function that will close that channel or write anything into that,
39:03
and another function will try to read from a channel, which means the function that tries to read from an empty channel will have to wait, and it will wait and it will wait and it will wait, and then when you close or write anything that doesn't have to make any sense, then that will progress,
39:21
which means having, well, coordinating two functions becomes super easy. If you share that channel across many functions, then all of the functions that are waiting for a channel when you close it will be able to progress. You can, of course, do it with mutexes, but why? Something called a latch,
39:43
you can also express with channels. Of course, there is some work that the worker is going to work on and so on and so on and so on. What can you imagine a latch with? You know what a horse race looks like. You know how it starts. There is this very fancy gate to which all the horses
40:01
have to enter, and then it's all released and then all of the horses start at once. This is the same concept actually in here. So you spawn a number of workers. You spawn, well, as many of them as you want, and they will do the work after they manage to read something from the latch.
40:21
Once that is closed or they can read something from here, they will be able to progress. When is it important? When is that fun? Each of the workers that you prepare has to read some configuration, has to be able to initialize themselves in a certain way. Maybe make a TCP connection,
40:41
maybe make an SSH connection. I don't know. It really depends on your use case, but this is a very, very frequent construct in many of the servers that we've written. It helps, and the fact that it's only, I don't know how many lines, but not too many. How many lines would that be in your language?
41:06
I can hear some whispers. I don't know what they say, but... It depends on the language. Of course, it depends on the language. That's a very good answer, but if you were to try to code it in Java, that would be a lot.
41:22
It certainly wouldn't fit on the screen in a readable way. I can promise you that. Generators. Another nice thing that Go has, you probably have used an SQL database. You've probably heard of sequences or a way to have sequential or non-sequential but unique numbers in a piece of software.
41:41
How can you make that in Go? It's, again, trivial. If you need some uniqueness, if you need something to govern over that, you can use a Go routine. The good thing is you use this funny-for construct. You write the current version of the counter
42:03
or your randomly generated version of the value into the channel, and then you generate another one. The great thing is it's lazy. This is only executed when the value is needed,
42:22
which means you don't have to worry about pre-generating all of the random values in the world or about the sizing. This Go routine will only be called upon when it's needed, which means having a sequential number generator that can be used across all of your Go routines
42:42
on a single machine becomes very easy. Of course, the problem becomes very complicated if you want to have a number of machines or a whole cluster or a number of clusters in different data centers, but this problem spans many runtimes, which means it's beyond what a programming language
43:01
should solve by default. But if you're still on a single machine, this gives you a generator. You can, of course, do other stuff in here. Also, if you want to have a single file interface or a single database connection, you can use that construct as well. Multiple channels at once, because it's good.
43:20
We've read from one channel, but what if there is a situation in which I want to read from a channel. Well, maybe there is this connection that will give me something. Maybe there is this connection that will give me something. How can I express that? Well, Go has a select statement which will just... It will advance and it will execute
43:42
the code that's associated with whichever case happens first. So you don't have to worry about expressing that with ifs or doing nested loops with... Or while... Or, well, yeah, looping and checking if something is available in the channel over and over and over.
44:00
It's available as a construct, which means you don't have to worry. Providing a default, there is a construct for that. And there is a timeout built in. How many times have you written a read from a socket or from somewhere and then forgotten about the timeout? I have done that many, many times. This still doesn't solve the problem,
44:21
because if I forget to put that in, I will forget, but it's easy to specify and it's built into the construct, so there is nothing extra that I have to use. That will be taken care of and that will be guarded by the runtime built in. Services. Assuming your software has... You're doing a microservice-based application
44:42
or just a service-based application and you want to create some services and the service has to stay available, but then comes the problem of how do we shut down in a graceful way? Because that's a nice way to shut things down, especially if you have connections to other services so that you don't leave them hanging, so that things don't have to timeout,
45:01
so that you don't waste resources. Well, you can create a service and spawn it and wait for it to do all the work. And then, again, you can use the channel to finish all the work, to signal that you have either completed your work or you're ready to die, which means you can use a quitting kind of notification,
45:23
like in here. So, make a channel. Well, do the work for three days or any amount of time that you need. You do the cleanup and then you... Well, you might report... This is just a sample, so it returns. It prints out to system out that you're done with the cleanup,
45:42
and then you quit. And then, when you have quit and the cleanup has happened, well, your governing piece of code can finish, exit in a nice way, and you're done. Buffered channels. Because I mentioned that there are unbuffered channels.
46:01
We skip the buffered ones for a reason. They are asynchronous. They will return a zero element when empty, and they will only wait when they are full. So, a buffered channel, a queue with a bounded size, your intuition guides you well. I've been talking about channels for more or less 15 minutes.
46:21
Somebody would ask, are channels the ultimate hammer? They are the silver, the golden bullet, whichever mythology you want to follow. And, of course, the fact that you can express a lot of the problems with channels doesn't mean that you should. So, Go also has the usual constructs,
46:42
like mutexes, like locks, like atomic operations. And those are screenshots from Go documentation that's available online about packages, about sync and sync atomic packages. So, those functions, those instructions, are built into the, well, already available to you.
47:01
You don't have to write them yourself, which means you don't have to create a double nested locking or some other idioms that you hope that you work, but they really don't. It's all, they're available for you. And last thing, if memory serves me well, are ranges.
47:21
So, a way of operating over channels or slices, which is a Go way of sync arrays, from a programmatic point of view. And the thing is, you can treat both in a single way. So, you can treat a slice
47:40
or you can treat a channel similarly, and you can just treat it, well, put that into the range instruction, so you can do a for loop over each, and then you don't have to learn two different syntaxes, because those things look the same and operate the same,
48:02
which, again, makes your software nicer to read, makes everything, well, makes life better. Packages, well, I mentioned that Go has packages when I showed you the package declaration. When I see what's available, I will see that there is a bin directory,
48:21
there is a package directory that will also generate things for specific architectures, which should lead you to a question, what about other architectures? What is the architecture support model with Go? Well, by default, if I compiled a program, a piece of software on a Mac,
48:41
I can put it, well, give it to a different Mac and it will run just fine. Of course it will not run on a Windows, of course it will not run on a Linux, but if I compile it on a Linux, I can get that binary, because, again, static linking, and ship it to a bunch of other Linux boxes and it will work, which is quite amazing. Can I cross-compile? Of course.
49:02
Can I do other funny things, well, compile against sources that have some C integration? Yes, of course. And I mentioned, somebody even asked about packages and dependencies, and I mentioned that Go already has a tool for that, and I can put imports that point at packages
49:24
that hover somewhere in the internet, and that's actually a very funny thing, because it's not specified in the language, so there is, how Go tools should resolve that, but it's assumed that Go tools will be able to resolve addresses like that.
49:41
So, if we go to here,
50:06
and then we do go get, and we hope that, oops, Google code doesn't like us anymore, oh well. What go get would do, is get the code from Google code,
50:23
if Google code would actually play with us today, it would download all the sources, it would download, well, the whole package. So, if you're used to binary packages being shipped around with tools like Maven, with tools like Ant, with other tools of choices,
50:41
in Go that's not the case. What you will download is the source code, so if you want to examine how something has been written, you will get to see exactly that. What it also means, you will download the source code with tests, assuming the tests are there, so you can run their tests if you suspect a bug. If you want to see the documentation,
51:01
documentation is part of the source code, it's embedded, which means you get to see it as well, which is an absolutely amazing concept if you're in a company that values open source software, and it makes working with proprietary libraries very awkward, but luckily, in my history I haven't had a situation so far
51:23
that I had to connect to a very proprietary library without having access to source code in Go. Maybe because the language and the ecosystem are quite young, maybe the mentality has changed, maybe the other environments are more frequent to exhibit such behavior.
51:44
So, Go get, well, we've tried to run it, it didn't work that well, so we'll skip that part. What looks bad? Well, if you want to have JSON structures and JSON kind of binding, the way that you have to express that in Go
52:03
looks a bit ugly to me. I'm not a huge fan of the syntax, because it connects your type definitions with how you should parse your data. It links two things together. It also means that the structure of your JSON
52:21
starts to live in your source code, which means you can't change one without the other, which is not the luckiest of choices. On the other hand, there are quite popular libraries that allow JSON and other format bindings for many languages out there, Java, Scala, most probably .NET, which means, well, that's something people look for.
52:43
Before you leave, before I say thank you and do you have any questions, if you wanted to learn Go, if you wanted to learn something more, of course, there is the excellent website which has a lot of tutorials. It has some of the tutorials. You can actually write code and run them through your browser. But if you'd like to do it the classical way, get a book,
53:03
this is the book I would recommend. It's written by, well, you can see the authors here, but I would say that it's quite amazing. It's very comprehensive. It's exactly as thick as your Kindle is, or, well, I haven't seen the paper version because I don't buy them anymore, but this will be my book of choice.
53:23
And last thing, what IDs should you write? Go in, well, pick your favorite text editor. You don't really need anything fancy. If you like Visual Studio Code, it has excellent Go support, including all of the additional tools that you can use,
53:41
like linting, like import, or automatic importing, like automatic formatting on safe. You can have that all in Visual Studio Code. I started writing Go with Sublime and I like it. Well, I love Sublime for that. You can, of course, do it in Vim. You can do it in Atom. You can do it in most of the other IDs out there as well because the language is very simple
54:02
because the syntax doesn't have any special cases. The type system is, again, simple, which means creating tools doesn't look that complex, but then all of the complexity shouldn't be in the software in how it gets written because it's not the smartest people who write the code.
54:21
It's about the problem that gets to be solved. So with that, I will ask you, well, try to download Go. Have some fun and Go code. And if you have any questions, just try to wave your hand. Yeah, there is a question.
54:40
Yeah, so handling errors by looking at return codes. Yes, the error variable that was returned from some of the instructions is if it's nil, if it's empty, that means that there is no error. If it's not nil, it should have the error information in it. It's not error codes as in integers.
55:02
Comparing that to things, you can use types. Well, there is a type system for your benefit here. But yeah, this is the approach here. So how can I protect myself from errors that somebody didn't think about? So if I ignore it, well, my software will explode
55:22
the same way other pieces of software will explode because, well, if it's the second parameter, nobody forces you to use it.
55:47
Well, there is a way which I don't have that example in the slides, but you don't have to assume if there is a tiny error in one of the small Go routines that there's something really not important that will crush your application.
56:01
No, there is a way to protect yourself from that, of course, but it's just not in the slides. ID support, well, we've covered. Debugging is also possible. C integration, well, how many minutes do we have? Three. Is anybody interested in C integration? No, no, no, no, good. So with that, I'll say thank you.
56:23
Enjoy lunch, enjoy coffees, enjoy all the great sponsors and everything else in the conference. It was my pleasure to see you and, well, experience Oslo, and I'll be available if you want to have any more conversations. Thanks.
56:44
There is this voting machine at the end. If you can please press the green button.