SlideShare uma empresa Scribd logo
1 de 41
Baixar para ler offline
Golang Dominicana:
Workshop
About me
Víctor S. Recio
CEO NerCore LLC,
@vsrecio / vrecio@nercore.com
Fundador y Organizador
● Docker Santo Domingo
● Linux Dominicana
● Golang Dominicana
● OpenSaturday.org
Software Developer Skills
Skills required for a software developer:
● Programming Language
● Text Editor
● Source Code Management
● Operating System
Activity*: 5 minute group discussion (_Icebreaker_)
Ground Rules
- Workshops are hard, everyone works at a different pace
- We will move on when about 50% are ready
- Slides are online, feel free to work ahead or catch up
Requirements
- Not need experience in some other language (Python, Ruby, Java, etc.)
- Know how to use Git version control system
- Comfortable with one shell (Bash, Zsh)
- Comfortable with one text editor (Vim, IntelliJ, Atom.)
- Install Go plugin for your text editor/IDE: VIM, IntelliJ, Atom
- Internet connectivity should be ensured
- Operating system with Go support (Linux, Mac OS. FreeBSD)
Agenda
- Format: talk, exercise, talk, exercise ... (short Q&A in between)
- General facts
- Running a hello world
- Reasons to use Go
- Development environment setup
- Types
- Control structures
- Data structures
- Functions
- Interfaces
- Concurrency
Facts
- General Purpose Programming Language
- Free and Open Source (FOSS)
- Created at Google by Robert Griesemer, Rob Pike and Ken Thompson
- Development started in 2007 and publicly released in November 2009
- C like syntax (no semicolons) (;)
- Object Oriented (Composition over inheritance - no classes!)
- Compiled (Statically linked)
- Garbage collected
- Statically typed
- Strongly typed
- built-in concurrency
- Two major compilers: gc & gccgo
- 25 keywords (less than C,C++,Python etc.)
- Classification (Capitalized are exported - public)
Facts
- Fast build (in seconds)
- Unused imports and variables raise compile error
- Operating Systems: Windows, GNU/Linux, Mac OS X, *BSD etc.
- CPU Architectures: amd64, i386, arm etc.
- Cross compilation
- Standard library
- No exceptions
- Pointers (No pointer arithmetic!)
Hello World!
package main
import "fmt"
func main() {
fmt.Println("Hello, Comunidad de Golang Dominicana!")
}
1
1
2
3
4
2
3
4
Este es conocido como declaracion de paquetes y es obligatorio.
Esta es la forma como incluimos código de otro paquete
Las funciones son los bloques de construcción de un programa en Go.
Las funciones poseen Input y Ouput y una serie de pasos llamados
declaraciones o sentencias.
Why Golang?
● Go compiles very quickly.
● Go supports concurrency at the language level.
● Functions are first class objects in Go.
● Go has garbage collection.
● Strings and maps are built into the language.
● Google is the owner
How are using Golang?
- Google
- Docker Inc.
- CoreOS
- Open Stack
- Digital Ocean
- AWS
- Twitter
- iron.io
https://github.com/golang/go/wiki/GoUsers
Installing Go on Linux
● Download Go compiler binary from https://golang.org/dl
● Extract it into your home directory (`$HOME/go`)
● Create directory named `mygo` in your home directory (`$HOME/mygo`)
● Add the following lines to your `$HOME/.bashrc`
# Variables Golang
export GOROOT=$HOME/go
export PATH=$GOROOT/bin:$PATH
export GOPATH=$HOME/mygo
export PATH=$GOPATH/bin:$PATH
● https://golang.org/doc/install
Building and Running
- You can run the program using "go run" command: go run hello.go
- You can also build (compile) and run the binary like this in GNU/Linux:
$ go build hello.go
$ ./hello
(The first command produce a binary and second command executes the binary)
Formatting Code
● Use "go fmt <file.go>" to format Go source file
● No more debate about formatting!
● Can integrate with editors like Vim, Emacs etc.
● *Proverb*: Gofmt's style is no one's favorite, yet gofmt is everyone's favorite.
(*Exercise*: 1)
Cross Compiling
● The "go build" command produce a binary file native to the operating system
and the architecture of the CPU (i386, x86_64 etc.)
● Specify targeted platform using environment variables: GOOS & GOARCH
● List of environment variables:
https://golang.org/doc/install/source#environment
GOOS=linux
GOARCH=x86-64
*Activity*: Produce binary for different operating systems and architectures
Formatting Code
● *$GOPATH* directory is a workspace (sources, packages, and binaries)
● Three sub-directories under $GOPATH: bin, pkg and src
● *bin* directory contains executable binaries (add to $PATH)
● The *src* directory contains the source files.
● The *pkg* directory contains package objects used by go tool to create the final
executable
● The Go tool understands the layout of a workspace
mygo
|-- bin
|-- pkg
|-- src
If you are using GitHub for hosting code, you can create a directory structure under
workspace like this:
src/github.com/<username>/<projectname>
Replace the <username> with your GitHub username or organization name and
<projectname> with the name of the project. For example:
src/github.com/vsrecio/demo
(*Note*: When you fork a project in Github use "go get" with the upstream location)
Getting third party packages
● The "go get" command download source repositories and places them in the
workspace
$ go get github.com/vsrecio/demo
$ go get golang.org/x/tools/...
● Repo URL and package path will be same normally (This helps Go tool to fetch)
● To update use "-u" flag
$ go get -u github.com/vsrecio/demo
- *Activity*: Run "go get" as given above
Exercise 1
Write a program to print ”Hello, World!” and save this in a file named
helloworld.go. Compile the program and run it like this:
$ ./helloworld
Go Tools
● Run "go help" to see list of available commands
● Use "go help [command]" for more information about a command
Few commonly used commands:
- build - compile packages and dependencies
- fmt - run gofmt on package sources
- get - download and install packages and dependencies
- install - compile and install packages and dependencies
- run - compile and run Go program
- test - test packages
- version - print Go version
Keywords
● Keywords are reserved words
● Cannot be used as identifiers
● Provide structure and meaning to the language
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
Comments
● Two kinds of comments
● C Style
/* This is a multi-line comment
... and this is a the second line
*/
● C++ style
// Single line number
// Starts with two slashes
*Activity*: Update the `hello.go` with few comments and run
Primitive types
int, uint, int8, uint8, ...
bool, string
float32, float64
complex64, complex128
package main
import "fmt"
func main() {
fmt.Printf("Value: %v, Type: %Tn", "Baiju", "Baiju")
fmt.Printf("Value: %v, Type: %Tn", 7, 7)
fmt.Printf("Value: %v, Type: %Tn" uint(7), uint(7))
fmt.Printf("Value: %v, Type: %Tn", int8(7), int8(7))
fmt.Printf("Value: %v, Type: %Tn" true, true)
fmt.Printf("Value: %v, Type: %Tn" 7.0, 7.0)
fmt.Printf("Value: %v, Type: %Tn" (1 + 6i), (1 + 6i))
}
Variables
● Type is explicitly specified but initialized with default zero values
● The zero value is 0 for numeric types, false for Boolean type and empty
string for strings.
package main
import "fmt"
func main() {
var age int
var tall bool
var name, place string
fmt.Printf("%#v, %#v, %#v, %#vn", age, tall, name, place)
}
● Type is explicitly specified and initialized with given values
package main
import "fmt"
func main() {
var age int = 10
var tall bool = true
var name, place string = "Baiju", "Bangalore"
fmt.Printf("%#v, %#v, %#v, %#vn", age, tall, name, place)
}
● Type is inferred from the values that is given for initialization
package main
import "fmt"
func main() {
var i = 10 // int
var s, b = "Baiju", true //string, bool
fmt.Printf("%#v, %#v, %#v, %#vn", i, s, b)
}
● Short variable declaration inside functions (Similar to above - type is inferred
from the values that is given for initialization)
package main
import "fmt"
func main() {
i := 10 // int
s, b := "Baiju", true //string, bool
fmt.Printf("%#v, %#v, %#v, %#vn", i, s, b)
}
Constants
● Constants are declared like variables, but with the const keyword.
● Constants can be character, string, Boolean, or numeric values.
● Constants cannot be declared using the := syntax.
const Male = true
const Pi = 3.14
const Name = "Baiju"
- *Activity*: Write a program to define the above constants and print it
Exercise 2
Write a program that converts from Fahrenheit into Celsius (C = (F - 32) * 5/9)
If Conditions
● Syntax inspired by C
● Curly brace is mandatory
package main
import "fmt"
func main() {
if 1 < 2 {
fmt.Printf("1 is less than 2")
}
}
● The if statement can start with a short statement to execute before the condition
● Variables declared by the statement are only in scope until the end of the if
● Variables declared inside an if short statement are also available inside any of
the else block
package main
import "fmt"
func main() {
if money := 20000; money > 15000 {
fmt.Println("I am going to buy a car.")
} else {
fmt.Println("I am going to buy a bike.")
}
// can't use the variable `money` here
}
Errors
● Go programs express error state with *error* values
● The error type is a built-in interface
● -Functions often return an error value, and calling code should handle
errors by testing whether the error equals *nil*.
package main
import ("fmt", "strconv")
func main() {
i, err := strconv.Atoi("42")
if err != nil {
fmt.Printf("couldn't convert number: %vn", err)
return
}
fmt.Println("Converted integer:", i)
}
Packages
● Every Go program is made up of packages
● Package name must be declared in source files
● To create executable use name of package as *main*
● Programs start running in package main
● All the package files resides in a directory
package main
● Import give access to exported stuff from other packages
● Any "unexported" names are not accessible from outside the package
● Foo is an exported name, as is FOO. The name foo is not exported
● By convention, package name is the same as the last element of the import
path
● Initialization logic for package goes into a function named *init*
● Use alias to avoid package name ambiguity with package imports
import (
"fmt"
"github.com/baijum/fmt"
)
Blank identifier
● Underscore (*_*) is the blank identifier
● Blank identifier can be used as import alias to invoke *init* function without
using the package
import (
"database/sql"
_ "github.com/lib/pq"
)
● Blank identifier can be used to ignore return values from function
x, _ := someFunc()
For Loop
● The only looping construct (no while loop)
● Syntax inspired by C
● No parenthesis (not even optional)
● Curly brace is mandatory
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println("Baiju")
}
}
Exercise 3
Write a program that prints all the numbers between 1 and 100, that are evently
divisible by 3 (3, 6,9).
Switch statement
● The cases are evaluated top to bottom until a match is found
● There is no automatic fall through
● Cases can be presented in comma-separated lists
● break statements can be used to terminate a switch early
package main
import (
"fmt"
"time"
)
func main() {
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.")
}
}
Defer statement
● Ensure a cleanup function is called later
● To recover from runtime panic
● Executed in LIFO order
package main
import "fmt"
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}
Write a program that prints all the numbers between 1 to 100, for multiples of
three, print “Fizz” instead of the number, and for the multiples of five, print
“Buzz”. For numbers that are multiples of both three and five, print “FizzBuzz”.
Exercise 4

Mais conteúdo relacionado

Mais procurados

Golang getting started
Golang getting startedGolang getting started
Golang getting startedHarshad Patil
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go langAmal Mohan N
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST APIFabien Vauchelles
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrencyjgrahamc
 
Go Programming Language by Google
Go Programming Language by GoogleGo Programming Language by Google
Go Programming Language by GoogleUttam Gandhi
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutinesNAVER Engineering
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingHaim Michael
 
Introduction to GoLang
Introduction to GoLangIntroduction to GoLang
Introduction to GoLangNVISIA
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)Ishin Vin
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular ComponentsSquash Apps Pvt Ltd
 

Mais procurados (20)

Golang getting started
Golang getting startedGolang getting started
Golang getting started
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
Go Language presentation
Go Language presentationGo Language presentation
Go Language presentation
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Go Programming Language by Google
Go Programming Language by GoogleGo Programming Language by Google
Go Programming Language by Google
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
Introduction to GoLang
Introduction to GoLangIntroduction to GoLang
Introduction to GoLang
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 
React-JS.pptx
React-JS.pptxReact-JS.pptx
React-JS.pptx
 

Destaque

Develop android application with mono for android
Develop android application with mono for androidDevelop android application with mono for android
Develop android application with mono for androidNicko Satria Consulting
 
Golang web database3
Golang web database3Golang web database3
Golang web database3NISCI
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnMoriyoshi Koizumi
 
La cuartarevindustrial_industrial: Internet de las cosas y big data. los pila...
La cuartarevindustrial_industrial: Internet de las cosas y big data. los pila...La cuartarevindustrial_industrial: Internet de las cosas y big data. los pila...
La cuartarevindustrial_industrial: Internet de las cosas y big data. los pila...Luis Joyanes
 
Ciberseguridad: Retos, oportunidades y riesgos de las tecnologías emergentes
Ciberseguridad: Retos, oportunidades y riesgos de las tecnologías emergentesCiberseguridad: Retos, oportunidades y riesgos de las tecnologías emergentes
Ciberseguridad: Retos, oportunidades y riesgos de las tecnologías emergentesLuis Joyanes
 
Internet de las cosas y Big Data. Los pilares de la cuarta revolución industrial
Internet de las cosas y Big Data. Los pilares de la cuarta revolución industrialInternet de las cosas y Big Data. Los pilares de la cuarta revolución industrial
Internet de las cosas y Big Data. Los pilares de la cuarta revolución industrialLuis Joyanes
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...SlideShare
 

Destaque (9)

CoreOS Overview
CoreOS OverviewCoreOS Overview
CoreOS Overview
 
Develop android application with mono for android
Develop android application with mono for androidDevelop android application with mono for android
Develop android application with mono for android
 
Golang web database3
Golang web database3Golang web database3
Golang web database3
 
Charla-Taller Git & GitHub
Charla-Taller Git & GitHubCharla-Taller Git & GitHub
Charla-Taller Git & GitHub
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
 
La cuartarevindustrial_industrial: Internet de las cosas y big data. los pila...
La cuartarevindustrial_industrial: Internet de las cosas y big data. los pila...La cuartarevindustrial_industrial: Internet de las cosas y big data. los pila...
La cuartarevindustrial_industrial: Internet de las cosas y big data. los pila...
 
Ciberseguridad: Retos, oportunidades y riesgos de las tecnologías emergentes
Ciberseguridad: Retos, oportunidades y riesgos de las tecnologías emergentesCiberseguridad: Retos, oportunidades y riesgos de las tecnologías emergentes
Ciberseguridad: Retos, oportunidades y riesgos de las tecnologías emergentes
 
Internet de las cosas y Big Data. Los pilares de la cuarta revolución industrial
Internet de las cosas y Big Data. Los pilares de la cuarta revolución industrialInternet de las cosas y Big Data. Los pilares de la cuarta revolución industrial
Internet de las cosas y Big Data. Los pilares de la cuarta revolución industrial
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
 

Semelhante a Golang workshop

C for Java programmers (part 1)
C for Java programmers (part 1)C for Java programmers (part 1)
C for Java programmers (part 1)Dmitry Zinoviev
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersAlessandro Sanino
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Robert Stern
 
The Go features I can't live without, 2nd round
The Go features I can't live without, 2nd roundThe Go features I can't live without, 2nd round
The Go features I can't live without, 2nd roundRodolfo Carvalho
 
Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programmingMahmoud Masih Tehrani
 
OSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with GoOSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with GoChris McEniry
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golangBasil N G
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io
 
Introduction to Programming in Go
Introduction to Programming in GoIntroduction to Programming in Go
Introduction to Programming in GoAmr Hassan
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
 
Go for SysAdmins - LISA 2015
Go for SysAdmins - LISA 2015Go for SysAdmins - LISA 2015
Go for SysAdmins - LISA 2015Chris McEniry
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with pythonroskakori
 
Don't Fear the Autotools
Don't Fear the AutotoolsDon't Fear the Autotools
Don't Fear the AutotoolsScott Garman
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMRaveen Perera
 
Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go languageTzar Umang
 

Semelhante a Golang workshop (20)

C for Java programmers (part 1)
C for Java programmers (part 1)C for Java programmers (part 1)
C for Java programmers (part 1)
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
Happy Go programing
Happy Go programingHappy Go programing
Happy Go programing
 
The Go features I can't live without, 2nd round
The Go features I can't live without, 2nd roundThe Go features I can't live without, 2nd round
The Go features I can't live without, 2nd round
 
Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programming
 
OSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with GoOSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with Go
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golang
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
Introduction to Programming in Go
Introduction to Programming in GoIntroduction to Programming in Go
Introduction to Programming in Go
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Go for SysAdmins - LISA 2015
Go for SysAdmins - LISA 2015Go for SysAdmins - LISA 2015
Go for SysAdmins - LISA 2015
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with python
 
Don't Fear the Autotools
Don't Fear the AutotoolsDon't Fear the Autotools
Don't Fear the Autotools
 
Comparing C and Go
Comparing C and GoComparing C and Go
Comparing C and Go
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
 
Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go language
 

Mais de Victor S. Recio

Mais de Victor S. Recio (6)

Docker images
Docker imagesDocker images
Docker images
 
Infraestructura
InfraestructuraInfraestructura
Infraestructura
 
Setting up a MySQL Docker Container
Setting up a MySQL Docker ContainerSetting up a MySQL Docker Container
Setting up a MySQL Docker Container
 
Docker up and running
Docker up and runningDocker up and running
Docker up and running
 
Docker Started
Docker StartedDocker Started
Docker Started
 
Presentation docker
Presentation dockerPresentation docker
Presentation docker
 

Último

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Último (20)

Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Golang workshop

  • 2. About me Víctor S. Recio CEO NerCore LLC, @vsrecio / vrecio@nercore.com Fundador y Organizador ● Docker Santo Domingo ● Linux Dominicana ● Golang Dominicana ● OpenSaturday.org
  • 3. Software Developer Skills Skills required for a software developer: ● Programming Language ● Text Editor ● Source Code Management ● Operating System Activity*: 5 minute group discussion (_Icebreaker_)
  • 4. Ground Rules - Workshops are hard, everyone works at a different pace - We will move on when about 50% are ready - Slides are online, feel free to work ahead or catch up
  • 5. Requirements - Not need experience in some other language (Python, Ruby, Java, etc.) - Know how to use Git version control system - Comfortable with one shell (Bash, Zsh) - Comfortable with one text editor (Vim, IntelliJ, Atom.) - Install Go plugin for your text editor/IDE: VIM, IntelliJ, Atom - Internet connectivity should be ensured - Operating system with Go support (Linux, Mac OS. FreeBSD)
  • 6. Agenda - Format: talk, exercise, talk, exercise ... (short Q&A in between) - General facts - Running a hello world - Reasons to use Go - Development environment setup - Types - Control structures - Data structures - Functions - Interfaces - Concurrency
  • 7. Facts - General Purpose Programming Language - Free and Open Source (FOSS) - Created at Google by Robert Griesemer, Rob Pike and Ken Thompson - Development started in 2007 and publicly released in November 2009 - C like syntax (no semicolons) (;) - Object Oriented (Composition over inheritance - no classes!) - Compiled (Statically linked) - Garbage collected - Statically typed - Strongly typed - built-in concurrency - Two major compilers: gc & gccgo - 25 keywords (less than C,C++,Python etc.) - Classification (Capitalized are exported - public)
  • 8. Facts - Fast build (in seconds) - Unused imports and variables raise compile error - Operating Systems: Windows, GNU/Linux, Mac OS X, *BSD etc. - CPU Architectures: amd64, i386, arm etc. - Cross compilation - Standard library - No exceptions - Pointers (No pointer arithmetic!)
  • 9. Hello World! package main import "fmt" func main() { fmt.Println("Hello, Comunidad de Golang Dominicana!") } 1 1 2 3 4 2 3 4 Este es conocido como declaracion de paquetes y es obligatorio. Esta es la forma como incluimos código de otro paquete Las funciones son los bloques de construcción de un programa en Go. Las funciones poseen Input y Ouput y una serie de pasos llamados declaraciones o sentencias.
  • 10. Why Golang? ● Go compiles very quickly. ● Go supports concurrency at the language level. ● Functions are first class objects in Go. ● Go has garbage collection. ● Strings and maps are built into the language. ● Google is the owner
  • 11. How are using Golang? - Google - Docker Inc. - CoreOS - Open Stack - Digital Ocean - AWS - Twitter - iron.io https://github.com/golang/go/wiki/GoUsers
  • 12. Installing Go on Linux ● Download Go compiler binary from https://golang.org/dl ● Extract it into your home directory (`$HOME/go`) ● Create directory named `mygo` in your home directory (`$HOME/mygo`) ● Add the following lines to your `$HOME/.bashrc` # Variables Golang export GOROOT=$HOME/go export PATH=$GOROOT/bin:$PATH export GOPATH=$HOME/mygo export PATH=$GOPATH/bin:$PATH ● https://golang.org/doc/install
  • 13. Building and Running - You can run the program using "go run" command: go run hello.go - You can also build (compile) and run the binary like this in GNU/Linux: $ go build hello.go $ ./hello (The first command produce a binary and second command executes the binary)
  • 14. Formatting Code ● Use "go fmt <file.go>" to format Go source file ● No more debate about formatting! ● Can integrate with editors like Vim, Emacs etc. ● *Proverb*: Gofmt's style is no one's favorite, yet gofmt is everyone's favorite. (*Exercise*: 1)
  • 15. Cross Compiling ● The "go build" command produce a binary file native to the operating system and the architecture of the CPU (i386, x86_64 etc.) ● Specify targeted platform using environment variables: GOOS & GOARCH ● List of environment variables: https://golang.org/doc/install/source#environment GOOS=linux GOARCH=x86-64 *Activity*: Produce binary for different operating systems and architectures
  • 16. Formatting Code ● *$GOPATH* directory is a workspace (sources, packages, and binaries) ● Three sub-directories under $GOPATH: bin, pkg and src ● *bin* directory contains executable binaries (add to $PATH) ● The *src* directory contains the source files. ● The *pkg* directory contains package objects used by go tool to create the final executable ● The Go tool understands the layout of a workspace mygo |-- bin |-- pkg |-- src
  • 17. If you are using GitHub for hosting code, you can create a directory structure under workspace like this: src/github.com/<username>/<projectname> Replace the <username> with your GitHub username or organization name and <projectname> with the name of the project. For example: src/github.com/vsrecio/demo (*Note*: When you fork a project in Github use "go get" with the upstream location)
  • 18. Getting third party packages ● The "go get" command download source repositories and places them in the workspace $ go get github.com/vsrecio/demo $ go get golang.org/x/tools/... ● Repo URL and package path will be same normally (This helps Go tool to fetch) ● To update use "-u" flag $ go get -u github.com/vsrecio/demo - *Activity*: Run "go get" as given above
  • 19. Exercise 1 Write a program to print ”Hello, World!” and save this in a file named helloworld.go. Compile the program and run it like this: $ ./helloworld
  • 20. Go Tools ● Run "go help" to see list of available commands ● Use "go help [command]" for more information about a command Few commonly used commands: - build - compile packages and dependencies - fmt - run gofmt on package sources - get - download and install packages and dependencies - install - compile and install packages and dependencies - run - compile and run Go program - test - test packages - version - print Go version
  • 21. Keywords ● Keywords are reserved words ● Cannot be used as identifiers ● Provide structure and meaning to the language break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return var
  • 22. Comments ● Two kinds of comments ● C Style /* This is a multi-line comment ... and this is a the second line */ ● C++ style // Single line number // Starts with two slashes *Activity*: Update the `hello.go` with few comments and run
  • 23. Primitive types int, uint, int8, uint8, ... bool, string float32, float64 complex64, complex128 package main import "fmt" func main() { fmt.Printf("Value: %v, Type: %Tn", "Baiju", "Baiju") fmt.Printf("Value: %v, Type: %Tn", 7, 7) fmt.Printf("Value: %v, Type: %Tn" uint(7), uint(7)) fmt.Printf("Value: %v, Type: %Tn", int8(7), int8(7)) fmt.Printf("Value: %v, Type: %Tn" true, true) fmt.Printf("Value: %v, Type: %Tn" 7.0, 7.0) fmt.Printf("Value: %v, Type: %Tn" (1 + 6i), (1 + 6i)) }
  • 24. Variables ● Type is explicitly specified but initialized with default zero values ● The zero value is 0 for numeric types, false for Boolean type and empty string for strings. package main import "fmt" func main() { var age int var tall bool var name, place string fmt.Printf("%#v, %#v, %#v, %#vn", age, tall, name, place) }
  • 25. ● Type is explicitly specified and initialized with given values package main import "fmt" func main() { var age int = 10 var tall bool = true var name, place string = "Baiju", "Bangalore" fmt.Printf("%#v, %#v, %#v, %#vn", age, tall, name, place) }
  • 26. ● Type is inferred from the values that is given for initialization package main import "fmt" func main() { var i = 10 // int var s, b = "Baiju", true //string, bool fmt.Printf("%#v, %#v, %#v, %#vn", i, s, b) }
  • 27. ● Short variable declaration inside functions (Similar to above - type is inferred from the values that is given for initialization) package main import "fmt" func main() { i := 10 // int s, b := "Baiju", true //string, bool fmt.Printf("%#v, %#v, %#v, %#vn", i, s, b) }
  • 28. Constants ● Constants are declared like variables, but with the const keyword. ● Constants can be character, string, Boolean, or numeric values. ● Constants cannot be declared using the := syntax. const Male = true const Pi = 3.14 const Name = "Baiju" - *Activity*: Write a program to define the above constants and print it
  • 29. Exercise 2 Write a program that converts from Fahrenheit into Celsius (C = (F - 32) * 5/9)
  • 30. If Conditions ● Syntax inspired by C ● Curly brace is mandatory package main import "fmt" func main() { if 1 < 2 { fmt.Printf("1 is less than 2") } }
  • 31. ● The if statement can start with a short statement to execute before the condition ● Variables declared by the statement are only in scope until the end of the if ● Variables declared inside an if short statement are also available inside any of the else block package main import "fmt" func main() { if money := 20000; money > 15000 { fmt.Println("I am going to buy a car.") } else { fmt.Println("I am going to buy a bike.") } // can't use the variable `money` here }
  • 32. Errors ● Go programs express error state with *error* values ● The error type is a built-in interface ● -Functions often return an error value, and calling code should handle errors by testing whether the error equals *nil*. package main import ("fmt", "strconv") func main() { i, err := strconv.Atoi("42") if err != nil { fmt.Printf("couldn't convert number: %vn", err) return } fmt.Println("Converted integer:", i) }
  • 33. Packages ● Every Go program is made up of packages ● Package name must be declared in source files ● To create executable use name of package as *main* ● Programs start running in package main ● All the package files resides in a directory package main
  • 34. ● Import give access to exported stuff from other packages ● Any "unexported" names are not accessible from outside the package ● Foo is an exported name, as is FOO. The name foo is not exported ● By convention, package name is the same as the last element of the import path ● Initialization logic for package goes into a function named *init* ● Use alias to avoid package name ambiguity with package imports import ( "fmt" "github.com/baijum/fmt" )
  • 35. Blank identifier ● Underscore (*_*) is the blank identifier ● Blank identifier can be used as import alias to invoke *init* function without using the package import ( "database/sql" _ "github.com/lib/pq" ) ● Blank identifier can be used to ignore return values from function x, _ := someFunc()
  • 36. For Loop ● The only looping construct (no while loop) ● Syntax inspired by C ● No parenthesis (not even optional) ● Curly brace is mandatory package main import "fmt" func main() { for i := 0; i < 5; i++ { fmt.Println("Baiju") } }
  • 37. Exercise 3 Write a program that prints all the numbers between 1 and 100, that are evently divisible by 3 (3, 6,9).
  • 38. Switch statement ● The cases are evaluated top to bottom until a match is found ● There is no automatic fall through ● Cases can be presented in comma-separated lists ● break statements can be used to terminate a switch early
  • 39. package main import ( "fmt" "time" ) func main() { 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.") } }
  • 40. Defer statement ● Ensure a cleanup function is called later ● To recover from runtime panic ● Executed in LIFO order package main import "fmt" func main() { defer fmt.Println("world") fmt.Println("hello") }
  • 41. Write a program that prints all the numbers between 1 to 100, for multiples of three, print “Fizz” instead of the number, and for the multiples of five, print “Buzz”. For numbers that are multiples of both three and five, print “FizzBuzz”. Exercise 4