SlideShare uma empresa Scribd logo
1 de 25
Introduction to
Go
Slawomir Dorzak
@sdorzak
About this presentation
● The point is to give you a "taste" of Go, not
to teach you how to programming in it
● I assume you know what an array and a
pointer is
● I'm not a Go expert
Quick history
● Invented by Robert Griesemer, Rob Pike
and Ken Thompson in 2007 (public in '09)
● Born out of a need for ease of programming
combined with type safety and portability
● Other goals:
○ Easy to learn
○ Type safety and memory safety
○ Easy concurrency via channels and "goroutines"
○ Low latency garbage collection
○ Fast compilation
Who is Ken Thompson?
Some companies using Go
● Canonical
● BBC
● Heroku
● CloudFoundry
● CloudFlare
● Bit.ly
● Google
IDE options
● Sublime Text 2
● IntelliJ
● LiteIDE
● Intype (Windows only)
● Netbeans
● Eclipse
● TextMate
● Komodo
● Zeus (Windows only)
Syntax overview
● It looks similar to C
● End of line semicolons are optional
● Variable declarations are optional
○ variable name is followed by it's type
■ var s string
○ variables can also be declared by initialization
■ i := 0
● Type conversions must be explicit
● Visibility is controlled using capitalization eg.
○ func Foo() will be publicly visible outside the
defining package
○ func bar() will be private
Interesting caveats
● Unused variables are a compilation error
● Unused import directives also
● No classes - Go is a procedural language
● No overloading
● No inheritance
Control structures
● If
● For
● Switch
That's it!
Control structures samples
if v := math.Pow(x, n); v < lim {
return v
} else {
fmt.Printf("%g >= %gn", v, lim)
}
Control structures samples
for i := 0; i < 10; i++ {
sum += i
}
for sum < 1000 {
sum += sum
}
for {
}
Control structures samples
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.")
}
Types
● Boolean - bool
● Numeric - uint8 to uint64, int8 to int64, uint, int, float32, float64,
complex64, complex128, byte, rune
● String - string
● Array eg. [5]byte, Slice eg. make([]int, 50, 100), Map eg. map
[string]int
● Struct - struct
● Pointer - *
● Function - func
● Interface - interface
● Channel - chan
Array
● Numbered sequence of elements of a single
type
● Fixed size
● Always one dimensional but can be
combined
● eg.
○ [32]byte
○ [2][8]int
○ [5]myStruct
○ [3]SomePublicInterface
○ [2]struct { x, y int32 }
○ b := [...]string{"Penn", "Teller"}
Slice
● Represents a segment of an array
● Like array - slice is one dimensional
● Slice does not have a fixed length
● Once initialized is always associated with
and underlying array
● Creating a slice:
○ make([]int, 50, 100)
○ new([100]int)[0:50]
○ letters := []string{"a", "b", "c", "d"}
Map
● It's a hash table implementeation in Go
● Provides fast lookup by given key
● Key can be any type that is comparable
● Value can be any type including another
map
● Order is not guaranteed
● Maps are not safe for concurrent use!
m := make(map[string]int)
m["val1"] = 1
m["val2"] = 2
for key, value := range m {
fmt.Println("Key:", key, "Value:", value)
}
Struct
● Structs are declared using struct keyword
● Only fields can be defined inside a struct
type Vertex struct {
X int
Y int
}
p := Vertex{1, 2}
Function
● Can return multiple values
● Unlike in C you can return address of a local
variable
● Functions can be "attached" to a struct or
interface
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := File{fd, name, nil, 0}
return &f
}
func (v Vertex)Print() string{
}
Sample code
package main
import "fmt"
// fib returns a function that returns successive Fibonacci numbers.
func fib() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return a
}
}
func main() {
f := fib()
// Function calls are evaluated left-to-right.
fmt.Println(f(), f(), f(), f(), f())
}
Interface
● Used to specify a behavior of an object
● A type can implement multiple interfaces
● Interfaces can be used in place of concrete
types
● Empty interface is met by any type
type Stringer interface {
ToString() string
}
Embedding
● a bit like inheritance
● allows to combine structs or interfaces
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
// ReadWriter is the interface that combines the Reader and Writer interfaces.
type ReadWriter interface {
Reader
Writer
}
Channels and goroutines
"Do not communicate by sharing memory;
instead, share memory by communicating"
● goroutine - is a lightweight concurrent
function (like thread)
● remove complexities of thread management
● channels are used for communicating
between goroutines
● they can be buffered or unbuffered
Example of using goroutines and
channels
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
}
c <- sum // send sum to c
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
What is go good for?
"large programs written by many developers,
growing over time to support networked
services in the cloud: in short, server software"
-- Rob Pike
Resources
● http://tour.golang.org
● http://golangtutorials.blogspot.ie
● http://golang.org/doc/effective_go.htm
● http://www.golang-book.com
● https://github.com/golang-samples

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Golang (Go Programming Language)
Golang (Go Programming Language)Golang (Go Programming Language)
Golang (Go Programming Language)
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Why you should care about Go (Golang)
Why you should care about Go (Golang)Why you should care about Go (Golang)
Why you should care about Go (Golang)
 
The Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventureThe Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventure
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Golang 101
Golang 101Golang 101
Golang 101
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go language
 
GoLang Introduction
GoLang IntroductionGoLang Introduction
GoLang Introduction
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golang
 
Go Programming Language by Google
Go Programming Language by GoogleGo Programming Language by Google
Go Programming Language by Google
 
Go lang
Go langGo lang
Go lang
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practice
 
Golang getting started
Golang getting startedGolang getting started
Golang getting started
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Go Language presentation
Go Language presentationGo Language presentation
Go Language presentation
 
Concurrency With Go
Concurrency With GoConcurrency With Go
Concurrency With Go
 
Golang workshop
Golang workshopGolang workshop
Golang workshop
 
GO programming language
GO programming languageGO programming language
GO programming language
 

Destaque

Destaque (9)

A First Look at Google's Go Programming Language
A First Look at Google's Go Programming LanguageA First Look at Google's Go Programming Language
A First Look at Google's Go Programming Language
 
Rust - Fernando Borretti
Rust - Fernando BorrettiRust - Fernando Borretti
Rust - Fernando Borretti
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers
 
Introduction to Go-Lang
Introduction to Go-LangIntroduction to Go-Lang
Introduction to Go-Lang
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
Golang
GolangGolang
Golang
 
[112] 실전 스위프트 프로그래밍
[112] 실전 스위프트 프로그래밍[112] 실전 스위프트 프로그래밍
[112] 실전 스위프트 프로그래밍
 
[132] rust
[132] rust[132] rust
[132] rust
 
An introduction to go programming language
An introduction to go programming languageAn introduction to go programming language
An introduction to go programming language
 

Semelhante a Introduction to Go programming language

Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
Kamil Toman
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
Eelco Visser
 

Semelhante a Introduction to Go programming language (20)

Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
 
Ready to go
Ready to goReady to go
Ready to go
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
 
Lua زبان برنامه نویسی
Lua زبان برنامه نویسی Lua زبان برنامه نویسی
Lua زبان برنامه نویسی
 
Go_ Get iT! .pdf
Go_ Get iT! .pdfGo_ Get iT! .pdf
Go_ Get iT! .pdf
 
Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!
 
Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
 
Let's Go-lang
Let's Go-langLet's Go-lang
Let's Go-lang
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
Auto Tuning
Auto TuningAuto Tuning
Auto Tuning
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
 
Python intro
Python introPython intro
Python intro
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
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
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Introduction to Go programming language

  • 2. About this presentation ● The point is to give you a "taste" of Go, not to teach you how to programming in it ● I assume you know what an array and a pointer is ● I'm not a Go expert
  • 3. Quick history ● Invented by Robert Griesemer, Rob Pike and Ken Thompson in 2007 (public in '09) ● Born out of a need for ease of programming combined with type safety and portability ● Other goals: ○ Easy to learn ○ Type safety and memory safety ○ Easy concurrency via channels and "goroutines" ○ Low latency garbage collection ○ Fast compilation
  • 4. Who is Ken Thompson?
  • 5. Some companies using Go ● Canonical ● BBC ● Heroku ● CloudFoundry ● CloudFlare ● Bit.ly ● Google
  • 6. IDE options ● Sublime Text 2 ● IntelliJ ● LiteIDE ● Intype (Windows only) ● Netbeans ● Eclipse ● TextMate ● Komodo ● Zeus (Windows only)
  • 7. Syntax overview ● It looks similar to C ● End of line semicolons are optional ● Variable declarations are optional ○ variable name is followed by it's type ■ var s string ○ variables can also be declared by initialization ■ i := 0 ● Type conversions must be explicit ● Visibility is controlled using capitalization eg. ○ func Foo() will be publicly visible outside the defining package ○ func bar() will be private
  • 8. Interesting caveats ● Unused variables are a compilation error ● Unused import directives also ● No classes - Go is a procedural language ● No overloading ● No inheritance
  • 9. Control structures ● If ● For ● Switch That's it!
  • 10. Control structures samples if v := math.Pow(x, n); v < lim { return v } else { fmt.Printf("%g >= %gn", v, lim) }
  • 11. Control structures samples for i := 0; i < 10; i++ { sum += i } for sum < 1000 { sum += sum } for { }
  • 12. Control structures samples 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.") }
  • 13. Types ● Boolean - bool ● Numeric - uint8 to uint64, int8 to int64, uint, int, float32, float64, complex64, complex128, byte, rune ● String - string ● Array eg. [5]byte, Slice eg. make([]int, 50, 100), Map eg. map [string]int ● Struct - struct ● Pointer - * ● Function - func ● Interface - interface ● Channel - chan
  • 14. Array ● Numbered sequence of elements of a single type ● Fixed size ● Always one dimensional but can be combined ● eg. ○ [32]byte ○ [2][8]int ○ [5]myStruct ○ [3]SomePublicInterface ○ [2]struct { x, y int32 } ○ b := [...]string{"Penn", "Teller"}
  • 15. Slice ● Represents a segment of an array ● Like array - slice is one dimensional ● Slice does not have a fixed length ● Once initialized is always associated with and underlying array ● Creating a slice: ○ make([]int, 50, 100) ○ new([100]int)[0:50] ○ letters := []string{"a", "b", "c", "d"}
  • 16. Map ● It's a hash table implementeation in Go ● Provides fast lookup by given key ● Key can be any type that is comparable ● Value can be any type including another map ● Order is not guaranteed ● Maps are not safe for concurrent use! m := make(map[string]int) m["val1"] = 1 m["val2"] = 2 for key, value := range m { fmt.Println("Key:", key, "Value:", value) }
  • 17. Struct ● Structs are declared using struct keyword ● Only fields can be defined inside a struct type Vertex struct { X int Y int } p := Vertex{1, 2}
  • 18. Function ● Can return multiple values ● Unlike in C you can return address of a local variable ● Functions can be "attached" to a struct or interface func NewFile(fd int, name string) *File { if fd < 0 { return nil } f := File{fd, name, nil, 0} return &f } func (v Vertex)Print() string{ }
  • 19. Sample code package main import "fmt" // fib returns a function that returns successive Fibonacci numbers. func fib() func() int { a, b := 0, 1 return func() int { a, b = b, a+b return a } } func main() { f := fib() // Function calls are evaluated left-to-right. fmt.Println(f(), f(), f(), f(), f()) }
  • 20. Interface ● Used to specify a behavior of an object ● A type can implement multiple interfaces ● Interfaces can be used in place of concrete types ● Empty interface is met by any type type Stringer interface { ToString() string }
  • 21. Embedding ● a bit like inheritance ● allows to combine structs or interfaces type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) } // ReadWriter is the interface that combines the Reader and Writer interfaces. type ReadWriter interface { Reader Writer }
  • 22. Channels and goroutines "Do not communicate by sharing memory; instead, share memory by communicating" ● goroutine - is a lightweight concurrent function (like thread) ● remove complexities of thread management ● channels are used for communicating between goroutines ● they can be buffered or unbuffered
  • 23. Example of using goroutines and channels func sum(a []int, c chan int) { sum := 0 for _, v := range a { sum += v } c <- sum // send sum to c } func main() { a := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(a[:len(a)/2], c) go sum(a[len(a)/2:], c) x, y := <-c, <-c // receive from c fmt.Println(x, y, x+y) }
  • 24. What is go good for? "large programs written by many developers, growing over time to support networked services in the cloud: in short, server software" -- Rob Pike
  • 25. Resources ● http://tour.golang.org ● http://golangtutorials.blogspot.ie ● http://golang.org/doc/effective_go.htm ● http://www.golang-book.com ● https://github.com/golang-samples