SlideShare a Scribd company logo
1 of 92
Download to read offline
Happy Go
Programming
PART I

林佑安
c9s
Intro
•

was the GitHub Top 1
Contributor ( http://git.io/top )

•

3+ years Perl/VimL
programming

•

3+ years PHP programming

•

2+ years Go programming
Go?
Ken Thompson
Rob Pike
Started since 2007
Announced in
November 2009
Used in some of Google’s
production system
What’s Go
•

Statically-Typed Language 靜態型別編譯語⾔言

•

Built-in Concurrency 內建並發性⽀支持

•

Statically-linked Native Binary 靜態連結原⽣生⼆二進位執⾏行檔

•

Fast compilation times 極快速的編譯

•

Remote package management 內建外部套件管理

•

Garbage Collection 使⽤用垃圾收集器

•

Safety 安全 (race conditions, type and memory safety for
multithreaded program)
About The Language
•

Concise variable declaration 簡潔的變數定義

•

Type Inference 型別推導

•

Easy to use 簡易使⽤用

•

Composition instead of Inheritance.

•

Use Interface 使⽤用介⾯面取代 is-a 繼承

•

multiple return value 多回傳值函數
About The Tools
•

語⾔言規格的修改,可透過 go fix 來將舊版語法或程式碼做⾃自
動修正

•

編碼⾵風格可透過 go fmt 來統⼀一所有格式,以及⾃自動去除空
⽩白⾏行、換⾏行、縮排等等。 且可以⽤用 grammar 的⽅方式來描述
語法。

•

內建 profiling tools 且⽀支持 Goole pprof ,可直接在 http
server 上開 profiler API,利⽤用命令列⼯工具遠端取得 CPU,
Memory 使⽤用狀況並進⾏行分析,或產⽣生 call graph 等等資
料。

•

遠端套件可直接透過 go get 安裝
What’s the difference?
那麼有什麼不同呢?
Statically-typed vs
Dynamically-typed
Statically-typed vs
Dynamically-typed
Statically-typed
languages are usually
faster
Benchmark
•

Faster than Node.js, Python, Perl, PHP, Ruby

•

A bit slower than C, C++ and Java (sometimes
faster than Java)

•

Low memory footprint (10+ times lower than Java)
Benchmark
http://www.techempower.com/benchmarks/
and it compiles fast
But it costs a lot of time
Go solves this
problem
Concurrency?
Prefork
Prefork
Prefork
Prefork
•

Hard to share data between processes.

•

Costs a lot of CPU cycle.

•

Copying process is time consuming.

•

Waste a lot of memory.
Just use Go Routine
Just use Go Routine

All in one process
Just use Go Routine
•

Threaded worker pool

•

use pipeline (channel) to communicate

•

CSP (Communicating Sequential Processes)

http://golang.org/doc/faq
Easier Deployment
Deployment Pain
•

Install required packages

•

Install application package dependencies

•

(dependency hell)

•

(incompatible version hell)

•

(10 hours later…)

•

ok, finally onlined.
You can just build &
scp
And it works
Q & A Time
————————
Ready For
Production?
Companies using Go
•

Google

•

Carbon Games

•

Sound Cloud

•

Iron.io

•

BCC

•

SmugMug

•

Canonical

•

Bitly

•

Heroku

•

CloudFlare
Enough Open
Sourced Packages?
15,298 packages
http://godoc.org/-/index
Is it popular?
Supported OS?
Supported OS
•

Linux

•

BSD, OpenBSD

•

Windows

•

Mac OS

•

Plan 9
Architectures?
Architectures
•

i386

•

amd64

•

arm
Q & A Time
————————
What You Will Learn
Today
Outline
•

Preparation
•

Installation / Build Go by yourself.

•

Hello World Go

•

Go commands

•

Go environment

•

Go packages

•

Editor and Environment for Go
Outline
•

Basic Syntax

•

Type

•

Built-in Types

•

Slice

•

Variable Declaration

•

Array

•

Function Declaration

•

Struct

•

Function Call

•

GoRoutine

•

Package

•

Channel
Outline
•

Write something
•

Your first command-line application.

•

Your first package.

•

Build & Install

•

Using built-in packages.

•

Using external packages.
Installation
•

Installation Guide: http://golang.org/doc/install

•

Go to https://code.google.com/p/go/downloads

•

Get your installer
Installation: Compile From Source
•

Install Mercurial:
•
•

port install mercurial

•
•

apt-get install mercurial

brew install mercurial

Go to http://golang.org/doc/install/source

hg clone -u release https://code.google.com/p/go
cd go/src
./all.bash
Environment
開發環境
Go IDE
•

Sublime Text 2

•

IntelliJ

•

LiteIDE

•

Intype

•

NetBeans

•

Eclipse

•

Zeus

http://geekmonkey.org/articles/20-comparison-of-ides-forgoogle-go
go/misc
•

misc/vim : generic vim plugin

•

misc/emacs : emacs go mode

•

misc/git : pre-commit hook (run go fmt before commmit)

•

misc/bash : bash completion

•

zsh/go : zsh completion

•

misc/cgo : cgo examples
vim: gocode

•

go completion daemon

•

vim omni completion support

•

scan code from $GOPATH
Go Environment
•

$GOROOT ( defaults to /usr/local/go )

•

$GOPATH ( your packages )

•

$GOARCH

•

$GOOS
$GOPATH
mkdir ~/go
export GOPATH=~/go

執⾏行 go get 時,packages 會安裝到
GOPATH 第⼀一個 path 內
$GOPATH
mkdir ~/go/vendor
mkdir ~/go/private
export GOPATH=~/go/vendor:~/go/private

可利⽤用 $GOPATH 將私⽤用 package 分開
$GOPATH
mkdir ~/go
export GOPATH=~/go

path

description

~/go/src

your source code

~/go/pkg

compiled packages (*.a)

~/go/bin

command-line binary
Hello World
$ vim hello.go
package main
!

import "fmt"
!

func main() {
fmt.Printf("hello, worldn")
}
Hello World
$ go run hello.go

$ go build -o hello hello.go
$ ./hello
Go commands
編譯後執⾏行程式 (必須是 main package)

•

go run

•

go build 編譯

•

go install 編譯並且安裝

•

go get 抓取遠端套件並且編譯安裝
Basic Syntax
Skeleton File
package main
!

// main application goes from here

package libraryA
!

// code goes from here
Built-in Type
•

int, int8, int16, int32, int64

•

uint, uint8, uint16, uint32, uint64

•

string

•

float32, float64
Variable
foo := 1
!

var foo = 1
!

var foo int = 1
!

bar := “foo bar”
var bar = “foo bar”
var bar string = “foo bar”
Variable Scope
foo := 1

var foo int = 1

!

!

{

{

}

foo := 2

}

var foo int = 2

!

!

// foo 1

// foo = 1
Variable Scope
foo := 1

var foo int = 1

!

!

for i := range list { for i := range list {
foo := 2
var foo int = 2
}
}
!

!

// foo 1

// foo = 1
Function Declaration
func FunctionName() {
// do something
}
Function Declaration

func FunctionName(x int) int {
return x * x
}
Function Call
!

func main() {
x := FunctionName(10)
}
Function Call With Package
package main
!

import “lib1”
!

func main() {
x := lib1.FunctionName(10)
}
Multiple Return Value
!

file, err := os.Open(“log.txt”)
if err != nil {
// handle error
}
Writing Your First
Command-line
Application in Go
Command-line package
•

package name should be named “main”

•

the directory name is the compiled binary name.

•

will be installed to $GOPATH/bin
Writing Your First Go
Package
General package
•

package name should be the same as directory
name.

•

located in $GOPATH/src

•

will be installed to $GOPATH/pkg
Array
items = […]int{ 1, 2, 3 }
!

items = [3]int{ 1, 2, 3 }
Slice
Slice
items = []int{ 1, 2, 3 }
Slice: Appending item
items = []int{ 1, 2, 3 }
!

items = append(items, 4)
Slice: Extracting
items = []int{ 1, 2, 3 }
!

copiedItems = items[:]
subItems = items[1:2]
Array vs Slice

•

Arrays are fixed-length. Slices are not.

•

Arrays are faster than slices.
Struct
Struct
•

Exported fields starts with upper case letter.

•

Private fields starts with lower case letter.

•

Code in the same package can access private
fields and private functions.

•

External package can not access private fields
and private functions.
Interface
Type Checking
Type Switch
Universal Interface
var x = interface{}
!

func Convert(a interface{}) {
// do the conversion

}
!

Convert(Foo{})
Convert(Bar{})
Convert(&Foo{})
Convert(&Bar{})
Thank you
•

Contact:
•

Twitter: @c9s

•

Plurk: @c9s

•

GitHub: @c9s

•

Facebook: http://facebook.com/yoan.lin

•

yoanlin93@gmail.com

More Related Content

What's hot

PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
Matt Harrison
 

What's hot (20)

Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Value protocols and codables
Value protocols and codablesValue protocols and codables
Value protocols and codables
 
Parse, scale to millions
Parse, scale to millionsParse, scale to millions
Parse, scale to millions
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Building Awesome CLI apps in Go
Building Awesome CLI apps in GoBuilding Awesome CLI apps in Go
Building Awesome CLI apps in Go
 
Hacking with hhvm
Hacking with hhvmHacking with hhvm
Hacking with hhvm
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from Data
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Golang
GolangGolang
Golang
 
Learning go for perl programmers
Learning go for perl programmersLearning go for perl programmers
Learning go for perl programmers
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Go lang introduction
Go lang introductionGo lang introduction
Go lang introduction
 
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programming
 
Php’s guts
Php’s gutsPhp’s guts
Php’s guts
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Php extensions
Php extensionsPhp extensions
Php extensions
 

Viewers also liked (11)

BT5攻防手法
BT5攻防手法BT5攻防手法
BT5攻防手法
 
程式設計師的自我修養 Chapter 5
程式設計師的自我修養 Chapter 5程式設計師的自我修養 Chapter 5
程式設計師的自我修養 Chapter 5
 
TLPI - Chapter 44 Pipe and Fifos
TLPI - Chapter 44 Pipe and FifosTLPI - Chapter 44 Pipe and Fifos
TLPI - Chapter 44 Pipe and Fifos
 
程式設計師的自我修養 Chapter 1
程式設計師的自我修養 Chapter 1程式設計師的自我修養 Chapter 1
程式設計師的自我修養 Chapter 1
 
程式設計師的自我修養 Chapter 10 記憶體
程式設計師的自我修養 Chapter 10 記憶體程式設計師的自我修養 Chapter 10 記憶體
程式設計師的自我修養 Chapter 10 記憶體
 
程式設計師的自我修養 Chapter 8
程式設計師的自我修養 Chapter 8程式設計師的自我修養 Chapter 8
程式設計師的自我修養 Chapter 8
 
An introduction to programming in Go
An introduction to programming in GoAn introduction to programming in Go
An introduction to programming in Go
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programming
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similar to Happy Go Programming Part 1

Unix Shell Scripting
Unix Shell ScriptingUnix Shell Scripting
Unix Shell Scripting
Mustafa Qasim
 
Package Management and Chef - ChefConf 2015
Package Management and Chef - ChefConf 2015Package Management and Chef - ChefConf 2015
Package Management and Chef - ChefConf 2015
Chef
 

Similar to Happy Go Programming Part 1 (20)

Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Go for SysAdmins - LISA 2015
Go for SysAdmins - LISA 2015Go for SysAdmins - LISA 2015
Go for SysAdmins - LISA 2015
 
Happy Go programing
Happy Go programingHappy Go programing
Happy Go programing
 
Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015
 
CommandBox at CFCamp 2014
CommandBox at CFCamp 2014CommandBox at CFCamp 2014
CommandBox at CFCamp 2014
 
Unix Shell Scripting
Unix Shell ScriptingUnix Shell Scripting
Unix Shell Scripting
 
Homebrew.pdf
Homebrew.pdfHomebrew.pdf
Homebrew.pdf
 
Go for Rubyists
Go for RubyistsGo for Rubyists
Go for Rubyists
 
Golang workshop
Golang workshopGolang workshop
Golang workshop
 
Bento lunch talk
Bento   lunch talkBento   lunch talk
Bento lunch talk
 
Package Management and Chef - ChefConf 2015
Package Management and Chef - ChefConf 2015Package Management and Chef - ChefConf 2015
Package Management and Chef - ChefConf 2015
 
Chef Conf 2015: Package Management & Chef
Chef Conf 2015: Package Management & ChefChef Conf 2015: Package Management & Chef
Chef Conf 2015: Package Management & Chef
 
Homebrew atlrug
Homebrew atlrugHomebrew atlrug
Homebrew atlrug
 
Ndc2017
Ndc2017Ndc2017
Ndc2017
 
Embedded Systems: Lecture 13: Introduction to GNU Toolchain (Build Tools)
Embedded Systems: Lecture 13: Introduction to GNU Toolchain (Build Tools)Embedded Systems: Lecture 13: Introduction to GNU Toolchain (Build Tools)
Embedded Systems: Lecture 13: Introduction to GNU Toolchain (Build Tools)
 
Django dev-env-my-way
Django dev-env-my-wayDjango dev-env-my-way
Django dev-env-my-way
 
Programming in Linux Environment
Programming in Linux EnvironmentProgramming in Linux Environment
Programming in Linux Environment
 
Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014
 
Effectively using Open Source with conda
Effectively using Open Source with condaEffectively using Open Source with conda
Effectively using Open Source with conda
 
Introduction to linux
Introduction to linuxIntroduction to linux
Introduction to linux
 

More from Lin Yo-An (11)

Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
 
Getting merged
Getting mergedGetting merged
Getting merged
 
OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
 
OSDC.TW 2014 building popular open source projects
OSDC.TW 2014   building popular open source projectsOSDC.TW 2014   building popular open source projects
OSDC.TW 2014 building popular open source projects
 
Secret sauce of building php applications
Secret sauce of building php applicationsSecret sauce of building php applications
Secret sauce of building php applications
 
LazyRecord: The Fast ORM for PHP
LazyRecord: The Fast ORM for PHPLazyRecord: The Fast ORM for PHP
LazyRecord: The Fast ORM for PHP
 
CPAN 模組二三事
CPAN 模組二三事CPAN 模組二三事
CPAN 模組二三事
 
Vim Hacks (OSSF)
Vim Hacks (OSSF)Vim Hacks (OSSF)
Vim Hacks (OSSF)
 
Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim Perlchina
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
Vim Hacks
Vim HacksVim Hacks
Vim Hacks
 

Recently uploaded

Recently uploaded (20)

Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
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
 
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?
 
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...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Happy Go Programming Part 1