This document provides an introduction to programming in Go. It discusses the origins and intentions of the Go language, where it is commonly used today, and what Go is and isn't. Go was created to be a systems programming language with better productivity than C++. It has seen widespread adoption beyond its original use cases. While Go isn't a functional or object-oriented language, it is compiled, statically typed, memory managed, concurrent, and ideal for building cloud infrastructure. The document also covers Go syntax including variables, types, loops, conditionals, functions, and more.
This presentation was given as a Workshop at OSCON 2014.
New to Go? This tutorial will give developers an introduction and practical
experience in building applications with the Go language. Gopher Steve Francia,
Author of [Hugo](http://hugo.spf13.com),
[Cobra](http://github.com/spf13/cobra), and many other popular Go packages
breaks it down step by step as you build your own full featured Go application.
Starting with an introduction to the Go language. He then reviews the fantastic
go tools available. With our environment ready we will learn by doing. The
remainder of the time will be dedicated to building a working go web and cli
application. Through our application development experience we will introduce
key features, libraries and best practices of using Go.
This tutorial is designed with developers in mind. Prior experience with any of the
following languages: ruby, perl, java, c#, javascript, php, node.js, or python
is preferred. We will be using the MongoDB database as a backend for our
application.
We will be using/learning a variety of libraries including:
* bytes and strings
* templates
* net/http
* io, fmt, errors
* cobra
* mgo
* Gin
* Go.Rice
* Cobra
* Viper
Go for Object Oriented Programmers or Object Oriented Programming without Obj...Steven Francia
Object Oriented (OO) programming has dominated software engineering for the last two decades. The paradigm built on powerful concepts such as Encapsulation, Inheritance, and Polymoprhism has been internalized by the majority of software engineers. Although Go is not OO in the strict sense, we can continue to leverage the skills we’ve honed as OO engineers to come up with simple and solid designs.
Gopher Steve Francia, Author of
[Hugo](http://hugo.spf13.com), [Cobra](http://github.com/spf13/cobra), and many
other popular Go packages makes these difficult concepts accessible for everyone.
If you’re a OO programmer, especially one with a background with dynamic languages and are curious about go then this talk is for you. We will cover everything you need to know to leverage your existing skills and quickly start coding in go including:
How to use our Object Oriented programming fundamentals in go
Static and pseudo dynamic typing in go
Building fluent interfaces in go
Using go interfaces and duck typing to simplify architecture
Common mistakes made by those coming to go from other OO languages (Ruby, Python, Javascript, etc.),
Principles of good design in go.
Given at GopherFest 2015. This is an updated version of the talk I gave in NYC Nov 14 at GothamGo.
“We need to think about failure differently. Most people think mistakes are a necessary evil. Mistakes aren't a necessary evil, they aren't evil at all. They are an inevitable consequence of doing something new and as such should be seen as valuable. “ - Ed Catmull
As Go is a "new" programming language we are all experimenting and learning how to write better Go. While most presentations focus on the destination, this presentation focuses on the journey of learning Go and the mistakes I personally made while developing Hugo, Cobra, Viper, Afero & Docker.
This presentation was given as a Workshop at OSCON 2014.
New to Go? This tutorial will give developers an introduction and practical
experience in building applications with the Go language. Gopher Steve Francia,
Author of [Hugo](http://hugo.spf13.com),
[Cobra](http://github.com/spf13/cobra), and many other popular Go packages
breaks it down step by step as you build your own full featured Go application.
Starting with an introduction to the Go language. He then reviews the fantastic
go tools available. With our environment ready we will learn by doing. The
remainder of the time will be dedicated to building a working go web and cli
application. Through our application development experience we will introduce
key features, libraries and best practices of using Go.
This tutorial is designed with developers in mind. Prior experience with any of the
following languages: ruby, perl, java, c#, javascript, php, node.js, or python
is preferred. We will be using the MongoDB database as a backend for our
application.
We will be using/learning a variety of libraries including:
* bytes and strings
* templates
* net/http
* io, fmt, errors
* cobra
* mgo
* Gin
* Go.Rice
* Cobra
* Viper
Go for Object Oriented Programmers or Object Oriented Programming without Obj...Steven Francia
Object Oriented (OO) programming has dominated software engineering for the last two decades. The paradigm built on powerful concepts such as Encapsulation, Inheritance, and Polymoprhism has been internalized by the majority of software engineers. Although Go is not OO in the strict sense, we can continue to leverage the skills we’ve honed as OO engineers to come up with simple and solid designs.
Gopher Steve Francia, Author of
[Hugo](http://hugo.spf13.com), [Cobra](http://github.com/spf13/cobra), and many
other popular Go packages makes these difficult concepts accessible for everyone.
If you’re a OO programmer, especially one with a background with dynamic languages and are curious about go then this talk is for you. We will cover everything you need to know to leverage your existing skills and quickly start coding in go including:
How to use our Object Oriented programming fundamentals in go
Static and pseudo dynamic typing in go
Building fluent interfaces in go
Using go interfaces and duck typing to simplify architecture
Common mistakes made by those coming to go from other OO languages (Ruby, Python, Javascript, etc.),
Principles of good design in go.
Given at GopherFest 2015. This is an updated version of the talk I gave in NYC Nov 14 at GothamGo.
“We need to think about failure differently. Most people think mistakes are a necessary evil. Mistakes aren't a necessary evil, they aren't evil at all. They are an inevitable consequence of doing something new and as such should be seen as valuable. “ - Ed Catmull
As Go is a "new" programming language we are all experimenting and learning how to write better Go. While most presentations focus on the destination, this presentation focuses on the journey of learning Go and the mistakes I personally made while developing Hugo, Cobra, Viper, Afero & Docker.
Introduction to go language programming , benchmark with another language programming nodejs , php , ruby & python . how install go . use what IDE . and rapid learnin golang
7 Common mistakes in Go and when to avoid themSteven Francia
I've spent the past two years developing some of the most popular libraries and applications written in Go. I've also made a lot of mistakes along the way. Recognizing that "The only real mistake is the one from which we learn nothing. -John Powell", I would like to share with you the mistakes that I have made over my journey with Go and how you can avoid them.
Python is a great programming language. It is a complete tutorial of using this programming language.
This slides is split into two parts, and it is the first part. Another part is at: http://www.slideshare.net/moskytw/programming-with-python-adv.
EuroPython 2016 - Do I Need To Switch To GolangMax Tepkeev
Nowadays, there is a lot of buzz about Go. It happened so that for the last 6 months I’ve been mostly programming Go, and frankly speaking I fell in love with this language.
We’ll first do a quick review of the language. Go doesn’t have some language constructs, for example classes and exceptions and at first it may seem hard to write proper Go code, but in practice the language is so easy that I will try to teach you the basics and most important concepts of the language. We’ll further discuss differences and similarities in Go and Python and dive into the cool features of Go.
Finally we’ll talk about why popularity of Go is raising so fast and try to answer the most important question: Do I need to switch to Go ?
pyconjp2015_talk_Translation of Python Program__Renyuan Lyu
Translation of Python Program into non-English Languages for Learners without English Proficiency,
a talk at Pycon Japan 2015, by Renyuan Lyu from Taiwan
It is the slides for COSCUP[1] 2013 Hands-on[2], "Learning Python from Data".
It aims for using examples to show the world of Python. Hope it will help you with learning Python.
[1] COSCUP: http://coscup.org/
[2] COSCUP Hands-on: http://registrano.com/events/coscup-2013-hands-on-mosky
Python is a great programming language. It is a complete tutorial of using this programming language.
This slides is split into two parts, and it is the second part. Another part is at: http://www.slideshare.net/moskytw/programming-with-python-basic.
Python offers several tool and public services that simplify starting and maintaining an open source project. This presentation show cases some of the most helpful one and explains the process, beginning with an empty folder and finishing with a published PyPI package.
Introduction to go language programming , benchmark with another language programming nodejs , php , ruby & python . how install go . use what IDE . and rapid learnin golang
7 Common mistakes in Go and when to avoid themSteven Francia
I've spent the past two years developing some of the most popular libraries and applications written in Go. I've also made a lot of mistakes along the way. Recognizing that "The only real mistake is the one from which we learn nothing. -John Powell", I would like to share with you the mistakes that I have made over my journey with Go and how you can avoid them.
Python is a great programming language. It is a complete tutorial of using this programming language.
This slides is split into two parts, and it is the first part. Another part is at: http://www.slideshare.net/moskytw/programming-with-python-adv.
EuroPython 2016 - Do I Need To Switch To GolangMax Tepkeev
Nowadays, there is a lot of buzz about Go. It happened so that for the last 6 months I’ve been mostly programming Go, and frankly speaking I fell in love with this language.
We’ll first do a quick review of the language. Go doesn’t have some language constructs, for example classes and exceptions and at first it may seem hard to write proper Go code, but in practice the language is so easy that I will try to teach you the basics and most important concepts of the language. We’ll further discuss differences and similarities in Go and Python and dive into the cool features of Go.
Finally we’ll talk about why popularity of Go is raising so fast and try to answer the most important question: Do I need to switch to Go ?
pyconjp2015_talk_Translation of Python Program__Renyuan Lyu
Translation of Python Program into non-English Languages for Learners without English Proficiency,
a talk at Pycon Japan 2015, by Renyuan Lyu from Taiwan
It is the slides for COSCUP[1] 2013 Hands-on[2], "Learning Python from Data".
It aims for using examples to show the world of Python. Hope it will help you with learning Python.
[1] COSCUP: http://coscup.org/
[2] COSCUP Hands-on: http://registrano.com/events/coscup-2013-hands-on-mosky
Python is a great programming language. It is a complete tutorial of using this programming language.
This slides is split into two parts, and it is the second part. Another part is at: http://www.slideshare.net/moskytw/programming-with-python-basic.
Python offers several tool and public services that simplify starting and maintaining an open source project. This presentation show cases some of the most helpful one and explains the process, beginning with an empty folder and finishing with a published PyPI package.
The future will be Realtime & CollaborativeJoseph Gentle
These are the slides from a talk I gave at the JS summit in 2014. I gave some demos too which were very cool. Hopefully the video will be available at some point.
When we ask ourselves why does God make us go through difficult times, we don’t realize the what/where these events may bring us. Only He knows and he will not let us fall. We don’t need to settle for the raw ingredients, trust in Him... And see something fantastic come about!
A brief introduction to Golang in a speech done @ Datio's headquarters in Madrid. I talked about it's drawbacks, strengths, compared with different languages and some of the tools that it provides as well as some exercises to test concurrency.
Lets Go - An introduction to Google's Go Programming Language Ganesh Samarthyam
This is an article to introduce Go language. Readers will have lots of questions when they come across a new (and promising) language, but because of limited space, I’ll cover only most important aspects of Go in this article.
OSCON2014 : Quick Introduction to System Tools Programming with GoChris McEniry
OSCON2014 Tutorial : Quick Introduction to System Tools Programming with Go
Every day, sysadmins are required to work with tools which, while powerful, tend to need to be merged with other languages. Many times, tools are chained together out of necessity by attempting to parse and munge outputs to inputs by making many inefficient calls to string processing command line tools. While effective, this approach is not usable in many situations due to the frequency of the run of the operation, or due to the footprint of the solution. Sometimes, it’s necessary to build your own tool, and the busy sysadmin needs one that is readily available.
Go’s powerful yet simple language makes it an excellent tool for harried sysadmins with limited time. Go’s toolset makes it easy to build and deploy simple small tools to targeted situations.
This tutorial provides an introduction to Go with a focus on using it for everyday sysadmins tooling. A example of working from iostat is used to show a practical approach to learning the language.
In this PPT you are going to know about Which is better, Java or Python? And how? and which has career? Meet the
Experts For better Guidence : https://nareshit.com/python-online-training/
Go is a new systems programming language from Google. Go has many interesting features such as 'communication channels' that makes it suitable for use in multi-core machines, and network programming. With Ken Thompson (of Unix fame) as one of its designers, Go has elegant and minimal design that is appealing to most programmers. This talk gives a technical introduction to Go that is of interest to anyone working in system software.
[Presentation I have in 2010 - I haven't updated it with recent changes to the Go language]
Golang basics for Java developers - Part 1Robert Stern
A short overview of Golang with Java comparison.
Part 1 of the series "Microservice development with Golang".
Contains hints and example links for potential Gophers
An introduction to the motivation behind the ooc project.
In a nutshell: software sucks, tools sucks, languages sucks - examples of what not to do. How ooc allows you to do pretty much aything with a few building blocks. An overview of the advantages/strong points of ooc.
These are the slides for the seminar to have a basic overview on the GO Language, By Alessandro Sanino.
They were used on a Lesson in University of Turin (Computer Science Department) 11-06-2018
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Why React Native as a Strategic Advantage for Startup Innovation.pdfayushiqss
Do you know that React Native is being increasingly adopted by startups as well as big companies in the mobile app development industry? Big names like Facebook, Instagram, and Pinterest have already integrated this robust open-source framework.
In fact, according to a report by Statista, the number of React Native developers has been steadily increasing over the years, reaching an estimated 1.9 million by the end of 2024. This means that the demand for this framework in the job market has been growing making it a valuable skill.
But what makes React Native so popular for mobile application development? It offers excellent cross-platform capabilities among other benefits. This way, with React Native, developers can write code once and run it on both iOS and Android devices thus saving time and resources leading to shorter development cycles hence faster time-to-market for your app.
Let’s take the example of a startup, which wanted to release their app on both iOS and Android at once. Through the use of React Native they managed to create an app and bring it into the market within a very short period. This helped them gain an advantage over their competitors because they had access to a large user base who were able to generate revenue quickly for them.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
4. Original intentions
Go has always been intended as a systems programming language (way at the bottom of the application
development stack).
In systems programming you would usually use C/C++ or Python if performance is not an issue for you as
productivity is.
5. Original intentions
Born out of mutual hatred towards writing and compiling C++ code.
To the surprise of the creators, Go has seen a much higher rate adoption from the scripting crowd
(Python and Ruby), and most of the C/C++ people perceived the simplicity of the langauge as a step back.
6. Where it is now
Seemingly everywhere
Go is 5 years old now.
To the surprise of its creators, it has grown tremendously in popularity.
It's the new go-to platform for building cloud infrastructure.
7. Where it is now
List of Go users(https://github.com/golang/go/wiki/GoUsers)
9. What Go isn't
Let's start by dialing down your expectations to a manageable level.
10. Go isn't a functional programming langauge
Although functions are first class objects
Go's adopted style is imperative through and through (sort of like C).
Your code is executed for its side effects, and you reason about your logic as sequential commands
executed to mutate some value within your scope of action.
Purely functional idioms in Go are really counter-productive.
So if you're a functional programming hipster, get over it.
11. Go isn't an object-oriented language
Although Go has objects.. with methods
And a limited way of doing inheritance (it's actually called composition)
It's not OOP-driven, and won't scratch your pure OOP itch.
Trying to construct rich type hierarchies like in Java or Python is very counter-productive.
12. Go isn't a high-level language
You might think that's implicit with "systems language", but it isn't. (cough) (Rust) (cough)
Go favors readability above all.
Go Offers just enough syntactic sugar to be productive, but not too much.
That is why a lot of the times verbosity and code simplicity are favored over complex succinctness.
15. Go is Compiled
Compiles to native hardware instructions that can run on the bear metal.
No overhead of a VM or an interpreter.
Comes at the price of doing cross-compilation when you need multiple OS support.
Don't worry, most of the stdlib is cross-compatible.
16. Go executables are statically-linked
Storage is cheap!
External dependencies and shared binaries are not worth the effort.
18. Go is statically-typed (awesomeness)
As you may know, I’m a bit biased towards static typing.
I just think it’s a really neat idea as it makes my life a lot easier.
19. Go is statically-typed
What is static typing anyway?
Unfortunately static typing has always had this stigma of it being too verbose.
This is not the case anymore in modern languages like Go, because of type inference.
So you kind of get the best of both worlds there.
20. Go is memory-managed
Go runtime is responsible for allocating memory for your objects.
You never need to worry about the correct (or incorrect) number of bytes to allocate.
Heap, stack or data segments are all fine with you.
21. Go is memory-managed
Go has a tracing garbage collector.
You never need to worry about who will deallocate your memory when.
You just use objects, pass them around and then stop using them.
22. Go is memory-managed
Unlike many other memory-managed programming languges, Go has memory pointers.
But since pointer arithmetic is unallowed (easily), it's considered safe.
Go is pragmatic
Built by software engineers (not academics) out of specific programming use cases, not in a "lab" or by
language designers.
Covers most of the areas that the creators felt needed addressing in their day-to-day programming
dendeavours.
23. Go is minimalistic
Small set of orthogonal features that provide a a sweet spot balance between programmer productivity
and simple software design.
Implies:
- Gentle learning curve
- Human-readable source code
It’s very common for people to pick up the language in an afternoon and start building things
immediately
Huge plus!
24. Go is modern
As a fairly-new language, the stdlibs come with packages for doing many of the essential jobs that a
programmer in this day would most likely require in her job.
Integrated web development stack and testing tools in the std libs and toolachain.
So no excuse to not be test-driven!
25. Go is concurrent
Dubbed a "concurrent language" because of support for native building blocks of concurrency built into
the syntax
Go's concurrency building blocks allow you to
- write and execute code concurrently directly from the language syntax
- establish managed (and safe) ways for communicating between concurrently executing code
26. Go is concurrent
The Go runtime will multiplex your concurrent code for you on actual OS threads, free of charge.
27. Go is a bit frustrating at first
First impressions of Go is that it's very lacking.
Go is almost never anyone’s first programming language, so everyone comes to it with expectations and
biases about how things should be done according to their system of belief and the kind of programming
idiom they are used to.
Since that Go was built out of frustration with the current state of things, it's meant to disrupt the way you
program.
28. Go is a bit frustrating at first
You shouldn't give into that initial frustration.
Because it gets rewarding very quickly.
30. Syntax
Most of these examples are derived from the official tour of Go on golang.org.
So if they seem too familiar, that’s probably the reason.
31. Syntax: Hello World
Execution starts in the main() in the "main" package.
UTF-8 source code files. No special headers. No literal escaping.
You can even declare unicode symbols.
Ω(DoSomething()).Should(Equal("foo"))
You probably shouldn't do that. Nice to know that you can though.
"fmt" is where you find string formatting functions.
"fmt" name is Rob Pike's doing.
package main
import "fmt"
func main() {
fmt.Println("Hello, ﻳﺎﺑﺸﺮ ")
} Run
32. Syntax: Variables
Variables can be declared in function scope of package scope.
package main
import "fmt"
var c, python, java bool
func main() {
var i int
fmt.Println(i, c, python, java)
} Run
33. Syntax: Variables with initializers
Type inference in action!
package main
import "fmt"
var i, j int = 1, 2
func main() {
var c, python, java = true, false, "no!"
fmt.Println(i, j, c, python, java)
} Run
34. Syntax: Shorthand variable declaration
Only inside a function body.
Both declarations are identical.
package main
import "fmt"
func main() {
var i, j int = 1, 2
k := 3
c, python, java := true, false, "no!"
fmt.Println(i, j, k, c, python, java)
} Run
35. Syntax: Primitive types
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
float32 float64
complex64 complex128
and
byte // alias for uint8
rune // alias for int32 and it represents a Unicode code point
Zero values for booleans is false and for numerical types an actual 0.
36. Syntax: Primitive types in action
package main
import (
"fmt"
"math/cmplx"
)
var (
ToBe bool = false
MaxInt uint64 = 1<<64 - 1
z complex128 = cmplx.Sqrt(-5 + 12i)
)
func main() {
const f = "%T(%v)n"
fmt.Printf(f, ToBe, ToBe)
fmt.Printf(f, MaxInt, MaxInt)
fmt.Printf(f, z, z)
} Run
37. Syntax: Type Conversion
Unlike in a lot of other languages where automatic conversion to types with wider percision is allowed,
type conversions in Go must be explicit.
The expression T(v) converts the value v to the type T.
package main
import (
"fmt"
"math"
)
func main() {
var x, y int = 3, 4
var f float64 = math.Sqrt(float64(x*x + y*y))
var z int = int(f)
fmt.Println(x, y, z)
} Run
40. Syntax: Loops - For Loop
Very C.
Parens are not allowed. Not even optional!
Body brakcets are obligatory.
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
} Run
41. Syntax: Loops - For Loop
package main
import "fmt"
func main() {
sum := 1
for ; sum < 1000; {
sum += sum
}
fmt.Println(sum)
} Run
42. Syntax: Loops - While Loop
package main
import "fmt"
func main() {
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum)
} Run
43. Syntax: While (TRUE) Loop
package main
import (
"fmt"
"time"
)
func main() {
for {
fmt.Println("Tick!")
time.Sleep(1000)
fmt.Println("Tock!")
time.Sleep(1000)
}
} Run
44. Syntax: Conditionals - If
Also very C.
Also body brakcets are obligatory
Again, parens are not even optional.
package main
import (
"fmt"
"math"
)
func sqrt(x float64) string {
if x < 0 {
return sqrt(-x) + "i"
}
return fmt.Sprint(math.Sqrt(x))
}
func main() {
fmt.Println(sqrt(2), sqrt(-4))
} Run
45. Syntax: Conditionals - If with pre-statement
package main
import (
"fmt"
"math"
)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
return lim
}
func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
} Run
46. Syntax: Conditionals - If/else
package main
import (
"fmt"
"math"
)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
} else {
fmt.Printf("%g >= %gn", v, lim)
}
// can't use v here, though
return lim
}
func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
} Run
47. Syntax: Conditionals - Switch
Switch is a fancy if with multiple if/else clauses.
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.", os)
}
} Run
48. Syntax: Conditionals - Switch case evaluation
switch i {
case 0:
case f():
}
The evaluation order of the switch case statements happens from top to bottom.
49. Syntax: Functions
The main building block in Go.
You can create nested closures using the func keyword.
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
sum := add(3, 1)
fmt.Println("Initial sum", sum)
// Closures! and first-class function values
incrementSum := func() { sum += 1 }
incrementSum()
incrementSum()
fmt.Println("Incremented sum", sum)
} Run
51. Syntax: Higher order functions
We can use function types to declare some higher order functions like
package main
import "fmt"
func add(a int, b int) int { return a + b }
func subtract(a, b int) int { return a - b }
func execute(a, b int, operation func(int, int) int) int { // shorthand for duplicate types
return operation(a, b)
}
func main() {
i, j := 4, 2
added := execute(i, j, add)
fmt.Printf("Added %d + %d == %dn", i, j, added)
subtracted := execute(i, j, subtract)
fmt.Printf("Subtracted %d - %d == %dn", i, j, subtracted)
} Run
52. Syntax: Defer
An awesome Go-first!
Push clean-up code to be executed before the function returns in LIFO.
Go's way of making up for not managing resources for you other than memory and CPU.
package main
import "fmt"
func main() {
defer fmt.Println("world")
fmt.Println("hello")
} Run
53. Syntax: Stacking defer statements
package main
import "fmt"
func main() {
fmt.Println("counting")
for i := 0; i < 10; i++ {
defer fmt.Println(i)
}
fmt.Println("done")
} Run
54. Syntax: Pointers
A Go pointer value is nothing but a typed memory addresses, much like a C pointer.
*T is a pointer to a T value
The zero value of a pointer is nil (no garbage values in Go).
55. Syntax: Pointers
This is how you declare a pointer.
var p *int
The & operator generates a pointer to its operand.
i := 42
p = &i
The * operator denotes the pointer's underlying value.
fmt.Println(*p) // read i through the pointer p
Dereferencing a pointer is also via the * operator.
*p = 21 // set i through the pointer p
Unlike C, Go has no pointer arithmetic.
56. Syntax: Structs
The the way of building heterogeneous aggregate custom types in Go.
That's fancy talk for saying it's a collection of fields of different types.
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
fmt.Println(Vertex{1, 2})
} Run
57. Syntax: Structs
Struct fields are accessible using the dot notation
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X)
} Run
58. Syntax: Struct literal notation
package main
import "fmt"
type Vertex struct {
X, Y int
}
var (
v1 = Vertex{1, 2} // has type Vertex
v2 = Vertex{X: 1} // Y:0 is implicit
v3 = Vertex{} // X:0 and Y:0
p = &Vertex{1, 2} // has type *Vertex
)
func main() {
fmt.Println(v1, p, v2, v3)
} Run
59. Syntax: Pointers to structs
Quickly instantiate and populate with values a struct all at once
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
p := &v
p.X = 1e9
fmt.Println(v)
} Run
60. Syntax: Structs are your main objects
If you’re coming from a strictly OOP language like Java, the only thing you would be thinking about in your
program design, is classes.
Classes this, classes that, classes everywhere.
61. Syntax: Structs are your main objects
Go creators did not like that approach where everything had to be a class.
Sometimes, the simplest most correct way to express your computation, is just as a function.
Go fell back to the minimalistic approach of C, where your data structures are just pure aggregate data.
And you can as an added bonus, you can specify type-specific operations on each of your custom types.
It’s like how in C you would declare struct s and then declare functions that all accept a pointer to the
struct as their first argument by convention.
62. Syntax: Struct methods
Two argument lists. First one only has the "receiver" argument. Second one has zero or more argumetns
of your method.
Dot notation for invoking struct methods on the receiver.
package main
import ("fmt"; "math")
type Vector struct {
X float64
Y float64
}
func (v Vector) Magnitude() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) }
func (v *Vector) Add(other *Vector) *Vector { return &Vector{X: v.X + other.X, Y: v.Y + other.Y} }
func main() {
vec := Vector{3.0, 4.0}
fmt.Println(vec)
fmt.Println(vec.Magnitude())
fmt.Println(vec.Add(&Vector{6.0, 4.0}))
} Run
63. Syntax: Arrays
The way of constructing homogeneous aggregate types in Go (a sequence of values of the same type).
Analogous to boring C arrays.
Fixed in size.
Size is part of the type.
package main
import "fmt"
func main() {
var a [2]string
a[0] = "Hello"
a[1] = "World"
fmt.Println(a[0], a[1])
fmt.Println(a)
} Run
64. Syntax: Slices
Slices are arrays on steroids.
Go makes up for the fact that it doesn’t let you do pointer arithmetic, by giving you this much cooler and
easier to use concept of slices.
A slice is more or less a view into a subset of an array.
[]T is a slice with elements of type T.
A slice's size is not reflected in its type.
65. Syntax: Slices
The slice literal notation lets you create slices backed by anonymous arrays very easily and populate them
with values on the spot.
Slices are used just like you would use an array, except for a couple of extra very neat features.
package main
import "fmt"
func main() {
p := []int{2, 3, 5, 7, 11, 13}
fmt.Println("p ==", p)
for i := 0; i < len(p); i++ {
fmt.Printf("p[%d] == %dn", i, p[i])
}
} Run
66. Syntax: Slicing slices
You can slice slices!
Very similar to sequence slicing in Python (except that negative indices are not supported).
You can slice into a slice to get a new view into its backing array, or you can slice into an already existing
array to get a slice from that.
package main
import "fmt"
func main() {
p := []int{2, 3, 5, 7, 11, 13}
fmt.Println("p ==", p)
fmt.Println("p[1:4] ==", p[1:4])
// missing low index implies 0
fmt.Println("p[:3] ==", p[:3])
// missing high index implies len(s)
fmt.Println("p[4:] ==", p[4:])
} Run
68. Syntax: Appending to slices
package main
import "fmt"
func main() {
var a []int
printSlice("a", a)
// append works on nil slices.
a = append(a, 0)
printSlice("a", a)
// the slice grows as needed.
a = append(a, 1)
printSlice("a", a)
// we can add more than one element at a time.
a = append(a, 2, 3, 4)
printSlice("a", a)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %vn",
s, len(x), cap(x), x)
} Run
69. Syntax: Appending to slices
If the backing array of the slice is too short, then append() would create a new backing array big enough
and use that in the returned slice.
70. Syntax: Maps
The native type-safe associative array in Go is the hash map, almost identical to the native map type in
Python.
71. Syntax: Maps
You must create a map using the make() function before usage, because the zero value of map is nil and
using that as a map causes in an error.
You can create maps from any type to any type.
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m map[string]Vertex
func main() {
m = make(map[string]Vertex)
m["Bell Labs"] = Vertex{
40.68433, -74.39967,
}
fmt.Println(m["Bell Labs"])
} Run
72. Syntax: Map Literals
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m = map[string]Vertex{
"Bell Labs": Vertex{
40.68433, -74.39967,
},
"Google": Vertex{
37.42202, -122.08408,
},
}
func main() {
fmt.Println(m)
} Run
74. Syntax: Range loops
21st century looping in Go
Similar to Python sequence looping
for i, v in enumerate([1, 2, 3])
and map looping
for k, v in mapping.items()
package main
import "fmt"
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
func main() {
for i, v := range pow {
fmt.Printf("2**%d = %dn", i, v)
}
} Run
76. The Zen of Go: Interfaces
Go resists this:
- subtype polymorphism (inheritance).
- parametric-type polymorphism (generics).
It instead emphasizes polymorphism via interfaces.
77. The Zen of Go: Interfaces
Go interfaces are small.
type Stringer interface {
String() string
}
A Stringer can pretty print itself.
Anything that implements String is a Stringer.
Interfaces are implemented implicitly.
78. The Zen of Go: Interfaces
Interfaces are types.
package main
import "fmt"
type Named interface {
Name() string
}
func greet(someone Named) { fmt.Println("Greetings, " + someone.Name()) }
type Human struct {
firstName string
}
func (h Human) Name() string {
return h.firstName
}
func main() {
greet(Human{firstName: "Jack Bauer"})
} Run
79. The Zen of Go: Interfaces
A Sorting example
package main
import ("fmt"; "sort")
type Person struct {
Name string
Age int
}
func (p Person) String() string { return fmt.Sprintf("%s: %d", p.Name, p.Age) }
// ByAge implements sort.Interface for []Person based on
// the Age field.
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func main() {
people := []Person{{"Bob", 31}, {"John", 42}, {"Michael", 17}, {"Jenny", 26}}
fmt.Println(people)
sort.Sort(ByAge(people))
fmt.Println(people)
} Run
81. The Zen of Go: Error handling
Unchecked exceptions are evil.
This is not scripting. You're building "robust" infrastructure software.
"Let it crash" cannot be the default way of handling errors.
Every computation that can fail must be executed with proper "error handling code".
82. The Zen of Go: Error handling
Memorize this pattern. You're gonna use it so much it'll haunt you in your dreams.
package main
import (
"fmt"
)
func getMyText() (string, error) {
// This could have been read from disk or a network socket
return "Your text", nil
}
func main() {
myText, err := getMyText()
if err != nil {
myText = "Sorry, I couldn't get your text. May I interest you in a joke?"
}
fmt.Println(myText)
} Run
83. The Zen of Go: Error handling
Go chose simplest approach possible to error handling.
Errors are plain regular values that implement the error interface.
type error {
Error() string
}
You should either handle an error or propagate it upwards.
84. The Zen of Go: Error handling
Unexpected errors should not be expected
package main
import ("fmt"; "regexp")
func extractLongestNumber(text string) string {
extractorRegexp, err := regexp.Compile("([0-9]+)")
if err != nil {
panic(err) // This will crash with a stack trace and the value of err
}
matches := extractorRegexp.FindStringSubmatch(text)
if len(matches) > 1 { return matches[1] } else { return "" }
}
func main() {
myText := "Sonmi-451"
fmt.Println(extractLongestNumber(myText))
} Run
85. The Zen of Go: Error handling
This is so common that there's a pattern for it.
package main
import ("fmt"; "regexp")
func extractLongestNumber(text string) string {
extractorRegexp := regexp.MustCompile("([0-9]+)")
matches := extractorRegexp.FindStringSubmatch(text)
if len(matches) > 1 { return matches[1] } else { return "" }
}
func main() {
myText := "Sonmi-451"
fmt.Println(extractLongestNumber(myText))
} Run
86. The Zen of Go: Error handling
Having to handle every each possible error case manually is a common first-day complaint in Go
You get used to it very quickly.
You will definitely feel its reward when you run your code and find it correct and not crashing the first
time.
88. The Zen of Go: Packages
Packages are one more thing that newcomers clash against.
Go comes with its own way of doing packages and file hierarchy for source code.
Just stop fighting it.
89. The Zen of Go: Packages
The first thing you'll do after installing the Go SDK is setting up your $GOPATH.
$GOPATH is structured like so:
|- src
|- bin
|- pkg
The import path of your packages is going to be the relative path under your $GOPATH/src directory.
Doing
import "coderize/awesomelib"
imports the package from $GOPATH/src/coderize/awesomelib as the awesomelib package
It's as simple as that. Don't invent your own system.
90. The Zen of Go: Visibility
Code visibility is only on the package level.
Only symbols starting with an upper class letter are exported.
package awesomelib
type ExportedType interface {
PublicAction()
}
type internalType struct {
internalNumber int
}
func (a internalType) PublicAction() { /* I work in silence*/ }
func internalDityWork() { /* TMI*/ }
func NewAwesomeness() ExportedType { /* TMI*/ return internalType{internalNumber: 42} }
92. The Zen of Go: Documentation
No special syntax.
Code documentation should be readable to humans in source code text format.
// Accepts an io.Reader and does the agreed-upon computation and returns the result
// or a descriptive error if something went wrong.
func ExportedFunction(reader io.Reader) (Result, error)
No special markup tags to describe parameters or return types.
If you make sure all your exported symbols are documented, Godoc can render that into perfectly
presentable HTML for you.
godoc(http://godoc.org/)
94. The Zen of Go: Concurrency
I've saved the best for last.
Concurrency is a session topic on its own.
Let's just skim over of what Go has to offer.
95. The Zen of Go: Concurrency
A goroutine is a lightweight thread managed by the Go runtime.
Go routines are multiplexed over multiple actual OS threads by the runtime.
go f(x, y, z)
starts a new goroutine running
f(x, y, z)
96. The Zen of Go: Concurrency
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
} Run
97. The Zen of Go: Concurrency
A channel is a typed synchronized queue.
boolChannel := make(chan bool) // I created a boolean channel of type "chan bool"
Channels are utilized for communication and synchronization between running goroutines.
There are three things you can do on a channel: send stuff, receive stuff, or close the channel.
boolChan <- = false
boolChan <- = true
boolChan <- = true
close(boolChan)
I just sent a "false" and two "true"s to the channel then closed it.
98. The Zen of Go: Concurrency
On the receiving end:
// Listens on the given channel for three incoming boolean messages and returns true if any one
// was true
func getMyBooleans(myChannel chan bool) bool {
firstMessage, isOpen := <- boolChan
if !isOpen {
return false
}
secondMessage, isOpen := <- boolChan
if !isOpen {
return firstMessage
}
thirdMessage, isOpen := <- boolChan
if !isOpen {
return firstMessage | secondMessage
}
return firstMessage | secondMessage | thirdMessage
}
99. The Zen of Go: Concurrency
Too verbose? range to the rescue:
// Listens on the given channel for incoming boolean messages and returns true if any one
// was true
func getMyBooleans(myChannel chan bool) bool {
message := false
for incomingMessage := myChannel {
message |= incomingMessage
}
return message
}
100. The Zen of Go: Concurrency
Channel sends and receives are blocking operations. So they're perfect for doing "lock-free"
synchronization.
101. The Zen of Go: Concurrency
Here's a really dumb example that takes too much time to compute
package main
import "fmt"
func fibonacci(i uint) uint {
if i <= 1 {
return 1
}
return fibonacci(i-1) + fibonacci(i-2)
}
func main() {
fmt.Println(fibonacci(41))
fmt.Println(fibonacci(41))
} Run
102. The Zen of Go: Concurrency
Same example but now made faster using parallelism via goroutines and channels.
package main
import "fmt"
func compute(computation func() int) <- chan int {
outputChannel := make(chan int)
go func() {
outputChannel <- computation()
}()
return outputChannel
}
func fibonacci(i int) int { if i <= 1 { return 1 } else {return fibonacci(i-1) + fibonacci(i-2) }}
func main() {
computation := func() int {return fibonacci(41)}
firstResult := compute(computation)
secondResult := compute(computation)
// Now I'm gonna block and wait for the two results
fmt.Println(<- firstResult)
fmt.Println(<- secondResult)
} Run
104. Where to Go from here (pun intended)
There are still several things that I did not have the time to cover in Go.
I suggest checking out the links below.
Take the Go tour yourself(http://tour.golang.org/)
Go for Gophers (by Andrew Gerrand)(https://talks.golang.org/2014/go4gophers.slide)
Go Concurrency Patterns (by the awesome Rob Pike)(https://www.youtube.com/watch?feature=player_detailpage&v=f6kdp27TYZs)
Go subreddit(http://www.reddit.com/r/golang)