Go is a statically typed, compiled programming language designed at Google in 2007 to improve programming productivity for multicore and networked machines. It addresses criticisms of other languages used at Google while keeping useful characteristics like C's performance, Python's readability, and support for high-performance networking and multiprocessing. Go is syntactically similar to C but adds memory safety, garbage collection, and CSP-style concurrency. There are two major implementations that target multiple platforms including WebAssembly. Go aims to guarantee that code written for one version will continue to build and run with future versions.
Stuart Fettinger's 6/13/2019 Chicago Microservices Meetup Presentation -
Title: Hurry Up and GO (But Not Too Fast)
Like all programming languages, GoLang can be great in some situations - not so great in others. We weigh GO against other frameworks, focusing on real-world examples to highlight benefits and common challenges. Plus, we explore how to architect and design efficient GO applications from the start, so you can limit your long-term technical debt.
The goal for this presentation is to cover the following:
- When you should and should not use GO
- Pros and cons of the language compared to others
- Efficient architecture and design, focusing on reuse and service patterns
Stuart Fettinger's 6/13/2019 Chicago Microservices Meetup Presentation -
Title: Hurry Up and GO (But Not Too Fast)
Like all programming languages, GoLang can be great in some situations - not so great in others. We weigh GO against other frameworks, focusing on real-world examples to highlight benefits and common challenges. Plus, we explore how to architect and design efficient GO applications from the start, so you can limit your long-term technical debt.
The goal for this presentation is to cover the following:
- When you should and should not use GO
- Pros and cons of the language compared to others
- Efficient architecture and design, focusing on reuse and service patterns
go programming language basics
This presentation is a copy of one of the presentation in the slideshare
i just walk through the basic side of go programming language
its about a 45 mins presentation
more details about this language you get from golang.org refer this link
New language from Google, static safe compiler, with GC and as fast as C++ or Java, syntax simpler then Python - 2 hour-long tutorial and you can start code.
In this talk Serhii will talk about Go, also known as Golang – an open source language developed at Google and used in production by companies such as Docker, Dropbox, Facebook and Google itself. Go is now heavily used as a general-purpose programming language that’s a pleasure to use and maintain. This introductory talk contains many live demos of basic language concepts, concurrency model, simple HTTP-based endpoint implementation and, of course, tests using build-in framework. This presentation will be interesting for backend engineers and DevOps to understand why Go had become so popular and how it might help to build robust and maintanable services.
Agenda of the presentation:
1. Go is not C, not Java, not anything
2. Rob Pike argument
3. Main ideas and basics
4. Concurrency model
5. Tools
6. Issues
Introduction to GoLang by Amal Mohan N. This presentation is an introduction to GoLang - it's history, features, syntax, importance etc.
concurrency, go-routines, golang, google, gopher, introduction, programming
Go, Golang, Golnguage, what is go language, what is go, History of go, Founders of Go, Why Go is invented ?, Why Go?, Who are using go today?, What will you see in Go?, What will you not see in Go?, Structure of Go Programs, Features of Go, Drawbacks of Go
A talk I gave at the Golang TO Meetup. Highlighting the beautiful powers of Go with respect to concurrency, and writing concurrent programs using it.
Code at: github.com/jsimnz/concurrency-talk
This tutorial will give you a brief introduction to both the languages Golang and Python. This Golang Vs. Python tutorial will compare both languages on various parameters such as Paradigms, Performance, Scalability, Application, Execution, Library, Readability and Memory Management. Further, you will get insights into the drawbacks of Golang and Python.
Below topics are covered in this tutorial:
What is Golang?
What is Python?
Key Differences between Golang and Python
Disadvantages of Golang
Disadvantages of Python
Go is a language developed by Google with multi-core in mind. Differ from other languages, concurrency is a first-class primitive in Go. This talk covers some useful patterns for dealing with concurrency.
An introduction into Googles programming language Go, which had its first release in March 2012. The talk has been held at the regulars' table of the GTUG Bremen.
go programming language basics
This presentation is a copy of one of the presentation in the slideshare
i just walk through the basic side of go programming language
its about a 45 mins presentation
more details about this language you get from golang.org refer this link
New language from Google, static safe compiler, with GC and as fast as C++ or Java, syntax simpler then Python - 2 hour-long tutorial and you can start code.
In this talk Serhii will talk about Go, also known as Golang – an open source language developed at Google and used in production by companies such as Docker, Dropbox, Facebook and Google itself. Go is now heavily used as a general-purpose programming language that’s a pleasure to use and maintain. This introductory talk contains many live demos of basic language concepts, concurrency model, simple HTTP-based endpoint implementation and, of course, tests using build-in framework. This presentation will be interesting for backend engineers and DevOps to understand why Go had become so popular and how it might help to build robust and maintanable services.
Agenda of the presentation:
1. Go is not C, not Java, not anything
2. Rob Pike argument
3. Main ideas and basics
4. Concurrency model
5. Tools
6. Issues
Introduction to GoLang by Amal Mohan N. This presentation is an introduction to GoLang - it's history, features, syntax, importance etc.
concurrency, go-routines, golang, google, gopher, introduction, programming
Go, Golang, Golnguage, what is go language, what is go, History of go, Founders of Go, Why Go is invented ?, Why Go?, Who are using go today?, What will you see in Go?, What will you not see in Go?, Structure of Go Programs, Features of Go, Drawbacks of Go
A talk I gave at the Golang TO Meetup. Highlighting the beautiful powers of Go with respect to concurrency, and writing concurrent programs using it.
Code at: github.com/jsimnz/concurrency-talk
This tutorial will give you a brief introduction to both the languages Golang and Python. This Golang Vs. Python tutorial will compare both languages on various parameters such as Paradigms, Performance, Scalability, Application, Execution, Library, Readability and Memory Management. Further, you will get insights into the drawbacks of Golang and Python.
Below topics are covered in this tutorial:
What is Golang?
What is Python?
Key Differences between Golang and Python
Disadvantages of Golang
Disadvantages of Python
Go is a language developed by Google with multi-core in mind. Differ from other languages, concurrency is a first-class primitive in Go. This talk covers some useful patterns for dealing with concurrency.
An introduction into Googles programming language Go, which had its first release in March 2012. The talk has been held at the regulars' table of the GTUG Bremen.
Asynchronous operations are getting more and more popular. To the point that we are getting frameworks and environments revolving strictly around that concept. Boost.ASIO, Twisted and node.js are notable example. We will not explore that area. We will focus on techniques for making asynchronous more readable. We will present different currently used solutions. At the end we will introduce coroutines and explain the concept. We will show how these can be integrated with asynchronous code and what we benefit from using coroutines in asynchronous code.
Go 1.10 Release Party, featuring what's new in Go 1.10 and a few deep dives into how Go works.
Presented at the PDX Go Meetup on April 24th, 2018.
https://www.meetup.com/PDX-Go/events/248938586/
Conférence des Geeks Anonymes sur " le langage Go ", par Thomas Hayen le 23 septembre 2020.
Cette conférence est disponible en vidéo sur Youtube : https://youtu.be/AlGGneVGTJk
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.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
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.
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.
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.
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
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.
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.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
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.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
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.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
2. Go is a statically typed, compiled programming language designed at Google in 2007 by Robert Griesemer(JVM, V8 JavaScript
engine),
Rob Pike(Unix, UTF-8), and Ken Thompson(B, C, Unix) to improve programming productivity in an era
of multicore, networked machines and large codebases.
The designers wanted to address criticism of other languages in use at Google, but keep their useful characteristics:
- Static typing and run-time efficiency (like C)
- Readability and usability (like Python or JavaScript)
- High-performance networking and multiprocessing
It is syntactically like C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency.
There are two major implementations:
1. Google's self-hosting "gc" compiler toolchain, targeting multiple operating systems and WebAssembly.
2. gofrontend, a frontend to other compilers, with the libgo library. With GCC the combination is gccgo; with LLVM the combination is
gollvm.
A third-party source-to-source compiler, GopherJS,[20] compiles Go to JavaScript for
front-end web development.
The guarantee: code written for Go 1.0 will build and run with Go 1.X.
6. Zero Values
var i int // my zero value is 0
var f float64 // my zero value is 0
var b bool // my zero value is false
var s string // my zero value is ""
8. Switch
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
fmt.Printf("%s.n", os)
}
// Switch with no condition
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
9. Pointers
func main() {
i, j := 42, 2701
p := &i // point to i
fmt.Println(*p) // read i through the pointer
*p = 21 // set i through the pointer
fmt.Println(i) // see the new value of i
p = &j // point to j
*p = *p / 37 // divide j through the pointer
fmt.Println(j) // see the new value of j
}
A pointer holds the memory address of a value.
10. Struct (“class”)
type Vertex struct {
X int
Y int
}
func NewVertex(x, y int) *Vertex{
return &Vertex{
X: x,
Y: y,
}
}
A struct is a collection of fields
12. Slices(“Lists”)
Slices are pointers to arrays, with the length of the
segment, and its capacity.
The length of a slice is the number of elements it contains.
The capacity of a slice is the number of elements in the
underlying array, counting from the first element in the
slice.
a := make([]int, 5) // len(a)=5
var s []int
// append works on nil slices.
s = append(s, 0)
What is the zero value of a slice?
13. Slices(“Lists”)
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)
}
for i := range pow {
pow[i] = 1 << uint(i) // == 2**i
}
for _, value := range pow {
fmt.Printf("%dn", value)
}
}
14. Maps
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"])
}
What is the zero value of a map?
15. Methods
Go does not have classes. However, you can define methods on types.
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
16. Methods
Choosing a value or pointer receiver
There are two reasons to use a pointer receiver.
The first is so that the method can modify the value that its receiver points to.
The second is to avoid copying the value on each method call.
This can be more efficient if the receiver is a large struct, for example.
In general, all methods on a given type should have either value or pointer
receivers, but not a mixture of both.
17. Enums
type AccountStatus int
const (
CreateInProgress AccountStatus = iota
CreateDone
CreateFailed
DeleteInProgress
DeleteFailed
)
func (a AccountStatus) String() string {
return [...]string{
"CreateInProgress",
"CreateDone",
"CreateFailed",
"DeleteInProgress",
"DeleteFailed",
}[a]
}
iota is an identifier that is used with constant, and which can
simplify constant definitions that use auto-increment
numbers. The iota keyword represents integer constant
starting from zero.
18. Interfaces
type Abser interface {
Abs() float64
}
type MyFloat float64
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
* Interface are pointers in GO!
Interfaces are named collections of method signatures.
19. Interfaces “trick”!
Let's say we are using a third-party library that defines this struct:
type Vertex struct {}
func (v *Vertex) DoSmt() float64 {
return 1.1
}
We can create an interface in our code and make Vertex struct implicity implement our interace!
It might be very usfull for unit testing.
type Bla interface {
DoSmt() float64
}
20. Composition(Embedding) over inheritance
type Request struct {
Resource string
}
type AuthenticatedRequest struct {
Request
Username, Password string
}
func main() {
ar := new(AuthenticatedRequest)
ar.Resource = "example.com/request"
ar.Username = "bob"
ar.Password = "P@ssw0rd"
fmt.Printf("%#v", ar)
}
Go supports embedding of structs and interfaces to
express a more seamless composition of types.
21. The empty interface (Any/Object)
The interface type that specifies zero methods is known as the
empty interface: interface{}
An empty interface may hold values of any type. (Every type implements at least zero
methods.)
22. Imports
1. Default import
2. Using alias
3. Access package content without typing the package name
4. Import a package solely for its side-effact (initialization)
import "fmt"
import format "fmt"
import . "fmt"
import _ "fmt"
24. Panic
A panic typically means something went unexpectedly wrong. Mostly we use it to fail
fast on errors that shouldn’t occur during normal operation, or that we aren’t
prepared to handle gracefully.
Running this program will cause it to panic, print an error message and goroutine
traces, and exit with a non-zero status.
func main() {
panic("a problem")
}
25. Defer
A defer statement defers the execution of a function until the
surrounding function returns.
When to use?
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}
26. Recover
Go makes it possible to recover from a panic, by using
the recover built-in function. A recover can stop a panic from aborting
the program and let it continue with execution instead.
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered. Error:n", r)
}
}()
mayPanic()
fmt.Println("After mayPanic()")
}
27. Error handling
Error handling in Golang is done through the built-in interface type, error.
It’s zero value is nil; so, if it returns nil, that means that there were no error.
By convention, errors are the last return value
func divide(x int, y int) (int, error) {
if y == 0 {
return -1, errors.New("Cannot divide by 0!")
}
return x/y, nil
}
func main() {
answer, err := divide(5,0)
if err != nil {
// Handle the error!
fmt.Println(err) // will print “Cannot divide by 0!”
} else {
// No errors!
fmt.Println(answer)
}
}
type error interface {
Error() string
}
28. Error handling – where is my stacktrace?
func FindUser(username string) (*db.User, error) {
u, err := db.Find(username)
if err != nil {
return nil, fmt.Errorf("FindUser: failed executing db query: %w", err)
}
return u, nil
}
func SetUserAge(u *db.User, age int) error {
if err := db.SetAge(u, age); err != nil {
return fmt.Errorf("SetUserAge: failed executing db update: %w", err)
}
}
func FindAndSetUserAge(username string, age int) error {
var user *User
var err error
user, err = FindUser(username)
if err != nil {
return fmt.Errorf("FindAndSetUserAge: %w", err)
}
if err = SetUserAge(user, age); err != nil {
return fmt.Errorf("FindAndSetUserAge: %w", err)
}
return nil
}
Calling FindAndSetUserAge result:
FindAndSetUserAge: SetUserAge: failed executing db update: malformed request
Golang authors thought that the stack trace should be printed
only on Panic to reduce the overhead of unwinding the call stack.
It goes hand in hand with the error handling approach -
since errors must be handled, the developer should take care also
for the stack trace.
However, if you still want a stack trace you can get it using go runtime/debug package.
There are some third-party libraries that can be used for that:
https://pkg.go.dev/golang.org/x/xerrors
https://github.com/pkg/errors
https://github.com/rotisserie/eris
30. Dependecies (Go Modules)
The go.mod file is the root of dependency management in GoLang.
All the modules which are needed or to be used in the project are
maintained in go.mod file.
After running any package building command like go build, go test for
the first time, it will install all the packages with specific versions i.e. which
are the latest at that moment.
It will also create a go.sum file which maintains the checksum so when you
run the project again it will not install all packages again. But use the cache
which is stored inside $GOPATH/pkg/mod directory
(module cache directory).
go.sum is a generated file you don’t have to edit or modify this file.
“require” will include all dependency modules and the related version we
are going to use in our project
“replace” points to the local version of a dependency in Go rather than the
git-web. It will create a local copy of a vendor with versions available so no
need to install every time when we want to refer the vendor.
“//indirect” implies that we are not using these dependencies inside our
project but there is some module which imports these.
all the transitive dependencies are indirect, these include dependencies
which our project needs to work properly.
31. Dependecies (Go Modules)
go mod tidy -
It will bind the current imports in the project and packages listed in go.mod.
It ensures that the go.mod file matches the source code in the module. It adds any missing
module requirements necessary to build the current module’s packages and dependencies, if
there are some not used dependencies go mod tidy will remove those from go.mod accordingly.
It also adds any missing entries to go.sum and removes unnecessary entries.
go mod vendor -
It generates a vendor directory with the versions available. It copies all third-party dependencies
to a vendor folder in your project root.
This will add all the transitive dependencies required in order to run the vendor package.
When vendoring is enabled, the go command will load packages from the vendor directory
instead of downloading modules from their sources into the module cache and using packages
those downloaded.
32. Generics
Starting with version 1.18, Go has added support for generics, also known
as type parameters.
func MapKeys[K comparable, V any](m map[K]V) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
func main() {
var m = map[int]string{1: "2", 2: "4", 4: "8"}
fmt.Println("keys:", MapKeys(m))
}
33. Context
A Context carries deadlines, cancellation signals, and other request-scoped values across API boundaries and
goroutines.
Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context.
The chain of function calls between them must propagate the Context, optionally replacing it with a derived
Context created using WithCancel, WithDeadline, WithTimeout, or WithValue.
When a Context is canceled, all Contexts derived from it are also canceled.
The WithCancel, WithDeadline, and WithTimeout functions take a Context (the parent) and return a derived
Context (the child) and a CancelFunc. Calling the CancelFunc cancels the child and its children, removes the
parent's reference to the child, and stops any associated timers. Failing to call the CancelFunc leaks the child
and its children until the parent is canceled or the timer fires.
The go vet tool checks that CancelFuncs are used on all control-flow paths.
- Do not pass a nil Context, even if a function permits it.
Pass context.TODO if you are unsure about which Context to use.
- Use context Values only for request-scoped data that transits processes and APIs,
not for passing optional parameters to functions.
- The same Context may be passed to functions running in different goroutines;
Contexts are safe for simultaneous use by multiple goroutines (context is immutable)
35. Unit Testing - Mocking
type MyRepo interface {
Get(ctx context.Context, id string) (interface{}, error)
Update(ctx context.Context, model interface{}) (interface{}, error)
}
type MyRepoImpl struct {
pg interface{}
}
func (m *MyRepoImpl) Get(ctx context.Context, id string) (interface{}, error) {
panic("implement me")
}
func (m *MyRepoImpl) Update(ctx context.Context, model interface{}) (interface{}, error) {
panic("implement me")
}
type MyRepoMock struct {
MockGet func(ctx context.Context, id string) (interface{}, error)
MockUpdate func(ctx context.Context, model interface{}) (interface{}, error)
}
func (a *MyRepoMock) Get(ctx context.Context, id string) (interface{}, error) {
return a.MockGet(ctx, id)
}
func (a *MyRepoMock) Update(ctx context.Context, model interface{}) (interface{}, error) {
return a.MockUpdate(ctx, model)
}
type MyService struct {
myRepo MyRepo
}
func (s *MyService) DoSmt(ctx context.Context) error {
// some logic...
model, err := s.myRepo.Get(ctx, "123")
if err != nil {
return err
}
// some logic...
}
36. Context - WithValue
func doSomething(ctx context.Context) {
fmt.Printf("doSomething: myKey's value is %sn", ctx.Value("myKey"))
}
func main() {
ctx := context.Background()
ctx = context.WithValue(ctx, "myKey", "myValue")
doSomething(ctx)
}
Output
doSomething: myKey's value is myValue
37. Context - WithCancel
func doSomething(ctx context.Context) {
ctx, cancelCtx := context.WithCancel(ctx)
printCh := make(chan int)
go doAnother(ctx, printCh)
for num := 1; num <= 3; num++ {
printCh <- num
}
cancelCtx()
time.Sleep(100 * time.Millisecond)
fmt.Printf("doSomething: finishedn")
}
func doAnother(ctx context.Context, printCh <-chan int) {
for {
select {
case <-ctx.Done():
if err := ctx.Err(); err != nil {
fmt.Printf("doAnother err: %sn", err)
}
fmt.Printf("doAnother: finishedn")
return
case num := <-printCh:
fmt.Printf("doAnother: %dn", num)
}
}
}
Output
doAnother: 1
doAnother: 2
doAnother: 3
doAnother err: context canceled
doAnother: finished
doSomething: finished
38. Context – WithDeadline / WithTimeout
const shortDuration = 1 * time.Millisecond
func main() {
d := time.Now().Add(shortDuration)
ctx, cancel := context.WithDeadline(context.Background(), d)
// Even though ctx will be expired, it is good practice to call its
// cancellation function in any case. Failure to do so may keep the
// context and its parent alive longer than necessary.
defer cancel()
select {
case <-time.After(1 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println(ctx.Err())
}
}
Output:
context deadline exceeded
39. Context – OpenTelemetry
OpenTelemetry also relies heavily on context for what is
called Context Propagation. That is a way to tied up
requests happening in different systems. The way to
implement that is to Inject span information into the
context you are going to send as part of the protocol you
are using (HTTP or gRPC, for instance). On the other
service you need to Extract the span information out of the
context.
40. Concurrency model
According to Rob Pike, concurrency is the composition of independently
executing computations, and concurrency is not parallelism: concurrency
is about dealing with lots of things at once, but parallelism is about doing
lots of things at once. Concurrency is about structure, parallelism is
about execution, concurrency provides a way to structure a solution to
solve a problem that may (but not necessarily) be parallelizable.
If you have only one processor, your program can still be concurrent, but it
cannot be parallel.
On the other hand, a well-written concurrent program might run efficiently in
parallel on a multiprocessor.
41. Goroutine
A goroutine is a lightweight thread(faster context switching & smaller size(2kB) compared with OS thread(1MB))
managed by the Go runtime.
It has its own call stack, which grows and shrinks as required.
It's very cheap. It's practical to have thousands, even hundreds of thousands of goroutines.
It's not a thread!
There might be only one thread in a program with thousands of goroutines.
Instead, goroutines are multiplexed dynamically onto threads as needed to keep all the goroutines running.
But if you think of it as a very cheap thread, you won't be far off.
The GOMAXPROCS variable limits the number of operating system threads
that can execute user-level Go code simultaneously.
There is no limit to the number of threads that can be blocked in system calls on behalf of Go code;
those do not count against the GOMAXPROCS limit. This package's GOMAXPROCS function
queries and changes the limit.
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")
}
42. Channels
Don't communicate by sharing memory, share memory by communicating!
A channel in Go provides a connection between two goroutines, allowing them to communicate.
// Declaring and initializing.
var c chan int
c = make(chan int)
// or
c := make(chan int)
// Sending on a channel.
c <- 1
// Receiving from a channel.
// The "arrow" indicates the direction of data flow.
value = <-c
43. Channels
Buffered Channels - Sends to a buffered channel block only when the buffer is full.
Receives block when the buffer is empty.
ch := make(chan int, 100)
A sender can close a channel to indicate that no more values will be sent.
Only the sender should close a channel, never the receiver!
Closing is only necessary when the receiver must be told there are no more
values coming!
v, ok := <-ch
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
func main() {
c := make(chan int, 10)
go fibonacci(cap(c), c)
for i := range c {
fmt.Println(i)
}
}
44. Channels
Channel Directions- When using channels as function parameters, you can specify if a channel is
meant to only send or receive values. This specificity increases the type-safety of the program.
This ping function only accepts a channel for sending values. It would be a compile-time error to try
to receive on this channel.
The pong function accepts one channel for receives (pings)
and a second for sends (pongs).
func ping(pings chan<- string, msg string) {
pings <- msg
}
func pong(pings <-chan string, pongs chan<- string) {
msg := <-pings
pongs <- msg
}
func main() {
pings := make(chan string, 1)
pongs := make(chan string, 1)
ping(pings, "passed message")
pong(pings, pongs)
fmt.Println(<-pongs)
}
45. Channels - Select
The select statement lets a goroutine wait on multiple
communication operations.
A select blocks until one of its cases can run, then it
executes that case. It chooses one at random if multiple
are ready.
A default clause, if present, executes immediately if no
channel is ready.
select {
case v1 := <-c1:
fmt.Printf("received %v from c1n", v1)
case v2 := <-c2:
fmt.Printf("received %v from c2n", v1)
case c3 <- 23:
fmt.Printf("sent %v to c3n", 23)
default:
fmt.Printf("no one was ready to communicaten")
}
46. Channels - Timeout using select
The time.After function returns a channel that blocks for the
specified duration.
After the interval, the channel delivers the current time, once.
func main() {
c := boring("Joe")
for {
select {
case s := <-c:
fmt.Println(s)
case <-time.After(1 * time.Second):
fmt.Println("You're too slow.")
return
}
}
}
47. WaitGroups
To wait for multiple goroutines to finish, we can use a wait group.
func worker(id int) {
fmt.Printf("Worker %d startingn", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d donen", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
worker(i)
}(i)
}
wg.Wait()
}
48. sync.Mutex
We've seen how channels are great for communication
among goroutines.
But what if we don't need communication? What if we just
want to make sure only one goroutine can access a
variable at a time to avoid conflicts?
This concept is called mutual exclusion, and the
conventional name for the data structure that provides it
is mutex.
// SafeCounter is safe to use concurrently.
type SafeCounter struct {
mu sync.Mutex
v map[string]int
}
// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
c.v[key]++
c.mu.Unlock()
}
// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Value(key string) int {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
defer c.mu.Unlock()
return c.v[key]
}
func main() {
c := SafeCounter{v: make(map[string]int)}
for i := 0; i < 1000; i++ {
go c.Inc("somekey")
}
time.Sleep(time.Second)
fmt.Println(c.Value("somekey"))
}
49. Atomic Counters
Here we’ll look at using the sync/atomic package for atomic
counters accessed by multiple goroutines.
func main() {
var ops uint64
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func() {
for c := 0; c < 1000; c++ {
atomic.AddUint64(&ops, 1)
}
wg.Done()
}()
}
wg.Wait()
fmt.Println("ops:", ops)
}
50. Go Fuzzing
Go supports fuzzing in its standard toolchain beginning in Go 1.18.
Fuzzing is a type of automated testing which continuously manipulates inputs to a
program to find bugs. Go fuzzing uses coverage guidance to intelligently walk
through the code being fuzzed to find and report failures to the user. Since it can
reach edge cases which humans often miss, fuzz testing can be particularly valuable
for finding security exploits and vulnerabilities.
51. Best practices
- Do not ignore errors.
- Handle error only once.
- Use Channels for goroutines comunication.
- Return an error instead of using Panic (especially in libs).
- Return an Error interface instead of a custom error struct.
- Do not be lazy; Use interfaces!
- Do not pass function arguments on context.Context.
- Pass context.Context as the first argument to a function.
- Do not use package level vars & func init(magic is bad; global state is magic).
- Handle errors in deferred functions.
- When choosing a third-party lib make sure it is following the GO
Standard lib(context.Context, net/http…).
- Avoid Reflection.
52. What is the output of this program?
var WhatIsThe = AnswerToLife()
func AnswerToLife() int {
println("Hello from AnswerToLife")
return 42
}
func init() {
println("Hello from init")
WhatIsThe = 0
}
func main() {
println("Hello from main")
if WhatIsThe == 0 {
println("It's all a lie.")
}
}
Hello from AnswerToLife
Hello from init
Hello from main
It's all a lie.
Do not use package level vars & func init!
magic is bad; global state is magic!
53. What would we like Go to be better at?
• Error handling (& stack trace).
• Function Overloading and Default Values for Arguments.
• Extension funcs.
• Get Goroutine “result” – like Kotlin Coroutines:
• Null safety
• Define Enum type
• Functional programming
• Macros / inline function
fun String.removeFirstLastChar(): String = this.substring(1, this.length - 1)
val result = "Hello Everyone".removeFirstLastChar()
val x string?
x?.toLowercase()
val deferred: Deferred<String> = async {
"Hello World"
}
val result = deferred.await()