SlideShare a Scribd company logo
Golang
2017.4.4 - 1
• Java, Node.js Golang
/
• Golang
2
Golang
• 2009 Google
• Robert C. Pike, Kenneth Lane Thompson UNIX
C
• :
• C , Limbo, Modul, Newsqueak, Oberon,
Pascal[3], Python
[Go ( ) - Wikipedia 3
Golang
•
•
•
•
• *
4
$ brew install golang
$ go version
go version go1.8 darwin/amd64
$ mkdir -p {golang } && cd $_
$ cat << _EOF_ >> ~/.bashrc
# Golang
export GOPATH=$(pwd)
export PATH=$PATH:$GOPATH/bin
_EOF_
$ exec $SHELL -l
5
Hello, World ...
Golang
$ tree -L 3
.
!"" bin # go build
#   !"" dep
#   $"" golint
!"" pkg # go get (vendor )
#   $"" darwin_amd64
#      $"" github.com
$"" src # ( / / )
!"" ghe.ca-tools.org
#   $"" montblanc
$"" mb2-shuffle
$"" github.com
   $"" seka
   $"" bbs-sample
6
Hello, World!
$ mkdir -p $GOPATH/src/github.com/{github }/helloworld && cd $_
main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
main.go
$ go run main.go
Hello, World!
7
: Go -Qiita
: github.com/seka/bbs-sample
Golang !
8
(1/2)
//
var [, ... ]
:=
//
const =
note: (
)
var num1 int32 = 10
var num2 int64 = 10
fmt.Println(num1 + num2) // mismatched types int32 and int64
fmt.Println(1 + "10") // mismatched types int and string
9
(2/2)
[n]T {}
[]T nil
error nil
struct{} {}
*T nil
interface{} nil
chan T nil message passing
note: The Go Programming Language Specification
10
(1/3)
//
a := [...]T{} //
b := [2][3]int{
{1, 2, 3},
{4, 5, 6},
}
//
a := make([]T,len) // a := []T{}
b := [][]int{
{1, 2, 3},
{4, 5, 6},
}
c := make([]T, len, cap)
11
(2/3)
Go Slice - Qiita
a := make([]int, 2)
a[0] = 0
a[1] = 1
b := a
fmt.Println(a) // [0 1]
fmt.Println(b) // [0 1]
b[0] = 10
fmt.Println(a) // [10 1]
fmt.Println(b) // [10 1]
b = append(b, 10)
fmt.Println(a) // [10 1]
fmt.Println(b) // [10 1 10]
b[0] = 20
fmt.Println(a) // [10 1]
fmt.Println(b) // [20 1 10]
12
(3/3)
size capacity
• capacity
• capacity size == capacity
note: capacity ...??
a := make([]int, 0, 1)
a = append(1)
fmt.Println(a) // [1] ...!
b := make([]int, 1)
b = append(a, 1)
fmt.Println(a) // [0, 1] ...??
13
(1/3)
func main() {
tmpfile, err := ioutil.TempFile("/tmp", "example-prefix")
if err != nil {
log.Fatal(err)
}
defer os.Remove(tmpfile.Name())
if _, err := tmpfile.Write([]byte("temporary file's content")); err != nil {
log.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
log.Fatal(err)
}
}
Golang
err
( bool )
14
(2/3)
...
!
Golang Error Handling lesson by Rob Pike - Block Rockin’ Codes
Golang pkg/errors | SOTA
note: Error func Error() string
15
(3/3)
panic/recover
func main() {
panicFunc()
}
func panicFunc() {
defer func() {
err := recover() //
log.Infoln("recover: ", err)
}()
panic("Panic!")
}
16
(1/2)
var struct {
[ ]
[ ]
}
type struct {
[ ]
[ ]
}
• :
• :
• : / ( )
17
(2/3)
struct
type Response struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
r := &Response{
Page: 1,
Fruits: []string{"apple", "peach", "pear"}
}
byts, _ := json.Marshal(r)
res2 := Response{}
if err := json.Unmarshal(byts, &res2); err != nil {
panic(err)
}
fmt.Println(dat)
18
(3/3)
•
• New[ ], new[ ]
func main() {
sample := newSampleStruct()
fmt.Println(sample.getNum())
fmt.Println(sample.Name)
}
type SampleStruct struct {
num int
Name string
}
func newSampleStruct() SampleStruct {
return SampleStruct{
num: 10,
Name: "Name field",
}
}
func (s SampleStruct) getNum() int {
return s.num
}
func (SampleStruct) sayHello() {
fmt.Println("Hello, World")
}
19
(1/3)
*T T &
var p *int
i := 42
p = &i
fmt.Println(i) // 42
fmt.Println(*p) // 42
*p = 100
fmt.Println(i) // 100
fmt.Println(*p) //100
note: C Golang C
20
(2/3)
func main() {
sample := newSampleStruct()
fmt.Println(sample.getNum())
fmt.Println(sample.Name)
}
type SampleStruct struct {
num int
Name string
}
func newSampleStruct() *SampleStruct {
return &SampleStruct{
num: 10,
Name: "Name field",
}
}
func (s *SampleStruct) getNum() int {
return s.num
}
func (*SampleStruct) sayHello() {
fmt.Println("Hello, World")
}
21
(3/3)
?
Go | Step by Step
...
•
•
• ( / / )
•
22
(1/5)
type interface {
( [, ...])
( [, ...]) ( [, ...]]])
}
•
• Golang
23
(2/5)
func main() {
var r geometry = &rect{width: 3, height: 4}
fmt.Println(r.area())
}
type geometry interface {
area() float64
}
type rect struct {
width, height float64
}
func (r rect) area() float64 {
return r.width * r.height
}
var _ geometry = (*rect)(nil) // TIPS
24
(3/5)
interface{}
func main() {
f("string") // string
f(100) // 100
f(true) // true
}
func f(x interface{}){
fmt.Println(x)
}
Golang interface{}
25
(4/5)
:
seka/mutexmaps: a utility mutex maps for Golang.
type StringMutexMap struct {
m *mutexmap.MutexMap
}
func newStringMutexMap() *StringMutexMap {
return &StringMutexMap{mutexmap.New(0)}
}
func (s *StringMutexMap) Get(key string) string {
item := s.m.Get(key)
return item.(string) // interface{} string
}
func (s *StringMutexMap) Put(key string, item string) {
s.m.Put(key, item) // string put
}
26
(4/5)
interface{}
func main() {
var i interface{} = "hello"
s := i.(string)
fmt.Println(s) // hello
f, ok := i.(float64)
fmt.Println(f, ok) // 0, false
switch t := i.(type) {
case string:
fmt.Println("string: ", i) // string: hello
default:
panic()
}
}
27
Golang (extends) (embedding)
type Model struct {
db database.Database
}
func NewModel(db database.Database) *Model {
return &Model{
db: db,
}
}
func (m *Model) Save(userID, msg string) error {
query := `INSERT INTO messages(user_id, message) VALUES (?, ?)`
_, err := m.db.Execute(query, userID, msg)
return err
}
28
Golang (1/3)
go func([ , ...]) {
}( )
go ([ , ...])
Golang goroutine
goroutine Golang
29
Golang (2/3)
ch := make(chan , )
ch <- // ch
:= <-ch // ch
close(ch) //
goroutine channel Message-passing
make
• : 0
• :
chan <- <-
30
Golang (3/3)
seka/bbs-sample
goroutine
goroutine <-sigs
os
func (m *Main) createSignalHandler() (context.Context, context.CancelFunc) {
sigs := make(chan os.Signal)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
go func() {
s := <-sigs
m.logger.Info("Got signal", "sigs", s)
cancel()
}()
return ctx, cancel
}
31
select
select {
case msg := <-ch2:
fmt.Println("received", msg)
case <-ch2:
fmt.Println("received")
}
select
( )
32

More Related Content

PDF
Let's golang
PDF
Go Concurrency
PDF
Why my Go program is slow?
PPT
Jan 2012 HUG: RHadoop
PDF
Golang Channels
PPTX
Hacking Go Compiler Internals / GoCon 2014 Autumn
PDF
Go Containers
KEY
Python 3
Let's golang
Go Concurrency
Why my Go program is slow?
Jan 2012 HUG: RHadoop
Golang Channels
Hacking Go Compiler Internals / GoCon 2014 Autumn
Go Containers
Python 3

What's hot (20)

DOCX
RedHat/CentOs Commands for administrative works
PDF
Gogo shell
PDF
Goroutines and Channels in practice
PDF
bpftrace - Tracing Summit 2018
KEY
PDF
Concurrency in Golang
PDF
Coding in GO - GDG SL - NSBM
PDF
Gnuplot 2
PPTX
Grokking TechTalk #16: Maybe functor in javascript
PDF
Javascript - The basics
PDF
The Art of Command Line (2021)
PDF
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
PDF
The Lesser Known Features of ECMAScript 6
KEY
サイ本 文
PDF
Python utan-stodhjul-motorsag
PDF
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
PDF
Bytes in the Machine: Inside the CPython interpreter
PDF
Docopt
PDF
Quicli - From zero to a full CLI application in a few lines of Rust
PDF
Programación funcional con haskell
RedHat/CentOs Commands for administrative works
Gogo shell
Goroutines and Channels in practice
bpftrace - Tracing Summit 2018
Concurrency in Golang
Coding in GO - GDG SL - NSBM
Gnuplot 2
Grokking TechTalk #16: Maybe functor in javascript
Javascript - The basics
The Art of Command Line (2021)
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
The Lesser Known Features of ECMAScript 6
サイ本 文
Python utan-stodhjul-motorsag
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
Bytes in the Machine: Inside the CPython interpreter
Docopt
Quicli - From zero to a full CLI application in a few lines of Rust
Programación funcional con haskell
Ad

Similar to Golang勉強会 (20)

PDF
Go, the one language to learn in 2014
PDF
JDD2014: GO! The one language you have to try in 2014 - Andrzej Grzesik
PPTX
Golang basics for Java developers - Part 1
PPTX
A Very Brief Intro to Golang
PDF
Introduction to go language programming
PDF
Something about Golang
PDF
Let's Go-lang
PDF
Golang
PDF
Golang workshop
PDF
Go Containers
PDF
Golang and Eco-System Introduction / Overview
PDF
Getting Started with Go
PPTX
Golang iran - tutorial go programming language - Preliminary
PPTX
golang_getting_started.pptx
PDF
LCA2014 - Introduction to Go
PPTX
The GO Language : From Beginners to Gophers
PDF
Go serving: Building server app with go
PDF
To GO or not to GO
PDF
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
PDF
Go for SysAdmins - LISA 2015
Go, the one language to learn in 2014
JDD2014: GO! The one language you have to try in 2014 - Andrzej Grzesik
Golang basics for Java developers - Part 1
A Very Brief Intro to Golang
Introduction to go language programming
Something about Golang
Let's Go-lang
Golang
Golang workshop
Go Containers
Golang and Eco-System Introduction / Overview
Getting Started with Go
Golang iran - tutorial go programming language - Preliminary
golang_getting_started.pptx
LCA2014 - Introduction to Go
The GO Language : From Beginners to Gophers
Go serving: Building server app with go
To GO or not to GO
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Go for SysAdmins - LISA 2015
Ad

More from Shin Sekaryo (10)

PPTX
ES6,7で書ける JavaScript
PPTX
再入門、サーバープッシュ技術
PPTX
ユーザーストーリーマッピング
PDF
Hello, Node.js
PDF
2013-Wingle-HotSpringHackathon(Winter)
PPT
2013-Wingle-HotSpringHackathon(Summer)
PDF
Systematic Romantic
PDF
FolkDance
KEY
LexuesAcademy-全体まとめ
PPTX
へっぽこPG奮闘記
ES6,7で書ける JavaScript
再入門、サーバープッシュ技術
ユーザーストーリーマッピング
Hello, Node.js
2013-Wingle-HotSpringHackathon(Winter)
2013-Wingle-HotSpringHackathon(Summer)
Systematic Romantic
FolkDance
LexuesAcademy-全体まとめ
へっぽこPG奮闘記

Recently uploaded (20)

PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Lecture Notes Electrical Wiring System Components
PDF
composite construction of structures.pdf
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
Construction Project Organization Group 2.pptx
PPTX
Sustainable Sites - Green Building Construction
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
DOCX
573137875-Attendance-Management-System-original
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
PPT on Performance Review to get promotions
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
UNIT 4 Total Quality Management .pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Foundation to blockchain - A guide to Blockchain Tech
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Lecture Notes Electrical Wiring System Components
composite construction of structures.pdf
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
CH1 Production IntroductoryConcepts.pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Construction Project Organization Group 2.pptx
Sustainable Sites - Green Building Construction
Operating System & Kernel Study Guide-1 - converted.pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Strings in CPP - Strings in C++ are sequences of characters used to store and...
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
573137875-Attendance-Management-System-original
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPT on Performance Review to get promotions
bas. eng. economics group 4 presentation 1.pptx
UNIT 4 Total Quality Management .pptx

Golang勉強会

  • 2. • Java, Node.js Golang / • Golang 2
  • 3. Golang • 2009 Google • Robert C. Pike, Kenneth Lane Thompson UNIX C • : • C , Limbo, Modul, Newsqueak, Oberon, Pascal[3], Python [Go ( ) - Wikipedia 3
  • 5. $ brew install golang $ go version go version go1.8 darwin/amd64 $ mkdir -p {golang } && cd $_ $ cat << _EOF_ >> ~/.bashrc # Golang export GOPATH=$(pwd) export PATH=$PATH:$GOPATH/bin _EOF_ $ exec $SHELL -l 5
  • 6. Hello, World ... Golang $ tree -L 3 . !"" bin # go build #   !"" dep #   $"" golint !"" pkg # go get (vendor ) #   $"" darwin_amd64 #      $"" github.com $"" src # ( / / ) !"" ghe.ca-tools.org #   $"" montblanc $"" mb2-shuffle $"" github.com    $"" seka    $"" bbs-sample 6
  • 7. Hello, World! $ mkdir -p $GOPATH/src/github.com/{github }/helloworld && cd $_ main.go package main import "fmt" func main() { fmt.Println("Hello, World!") } main.go $ go run main.go Hello, World! 7
  • 8. : Go -Qiita : github.com/seka/bbs-sample Golang ! 8
  • 9. (1/2) // var [, ... ] := // const = note: ( ) var num1 int32 = 10 var num2 int64 = 10 fmt.Println(num1 + num2) // mismatched types int32 and int64 fmt.Println(1 + "10") // mismatched types int and string 9
  • 10. (2/2) [n]T {} []T nil error nil struct{} {} *T nil interface{} nil chan T nil message passing note: The Go Programming Language Specification 10
  • 11. (1/3) // a := [...]T{} // b := [2][3]int{ {1, 2, 3}, {4, 5, 6}, } // a := make([]T,len) // a := []T{} b := [][]int{ {1, 2, 3}, {4, 5, 6}, } c := make([]T, len, cap) 11
  • 12. (2/3) Go Slice - Qiita a := make([]int, 2) a[0] = 0 a[1] = 1 b := a fmt.Println(a) // [0 1] fmt.Println(b) // [0 1] b[0] = 10 fmt.Println(a) // [10 1] fmt.Println(b) // [10 1] b = append(b, 10) fmt.Println(a) // [10 1] fmt.Println(b) // [10 1 10] b[0] = 20 fmt.Println(a) // [10 1] fmt.Println(b) // [20 1 10] 12
  • 13. (3/3) size capacity • capacity • capacity size == capacity note: capacity ...?? a := make([]int, 0, 1) a = append(1) fmt.Println(a) // [1] ...! b := make([]int, 1) b = append(a, 1) fmt.Println(a) // [0, 1] ...?? 13
  • 14. (1/3) func main() { tmpfile, err := ioutil.TempFile("/tmp", "example-prefix") if err != nil { log.Fatal(err) } defer os.Remove(tmpfile.Name()) if _, err := tmpfile.Write([]byte("temporary file's content")); err != nil { log.Fatal(err) } if err := tmpfile.Close(); err != nil { log.Fatal(err) } } Golang err ( bool ) 14
  • 15. (2/3) ... ! Golang Error Handling lesson by Rob Pike - Block Rockin’ Codes Golang pkg/errors | SOTA note: Error func Error() string 15
  • 16. (3/3) panic/recover func main() { panicFunc() } func panicFunc() { defer func() { err := recover() // log.Infoln("recover: ", err) }() panic("Panic!") } 16
  • 17. (1/2) var struct { [ ] [ ] } type struct { [ ] [ ] } • : • : • : / ( ) 17
  • 18. (2/3) struct type Response struct { Page int `json:"page"` Fruits []string `json:"fruits"` } r := &Response{ Page: 1, Fruits: []string{"apple", "peach", "pear"} } byts, _ := json.Marshal(r) res2 := Response{} if err := json.Unmarshal(byts, &res2); err != nil { panic(err) } fmt.Println(dat) 18
  • 19. (3/3) • • New[ ], new[ ] func main() { sample := newSampleStruct() fmt.Println(sample.getNum()) fmt.Println(sample.Name) } type SampleStruct struct { num int Name string } func newSampleStruct() SampleStruct { return SampleStruct{ num: 10, Name: "Name field", } } func (s SampleStruct) getNum() int { return s.num } func (SampleStruct) sayHello() { fmt.Println("Hello, World") } 19
  • 20. (1/3) *T T & var p *int i := 42 p = &i fmt.Println(i) // 42 fmt.Println(*p) // 42 *p = 100 fmt.Println(i) // 100 fmt.Println(*p) //100 note: C Golang C 20
  • 21. (2/3) func main() { sample := newSampleStruct() fmt.Println(sample.getNum()) fmt.Println(sample.Name) } type SampleStruct struct { num int Name string } func newSampleStruct() *SampleStruct { return &SampleStruct{ num: 10, Name: "Name field", } } func (s *SampleStruct) getNum() int { return s.num } func (*SampleStruct) sayHello() { fmt.Println("Hello, World") } 21
  • 22. (3/3) ? Go | Step by Step ... • • • ( / / ) • 22
  • 23. (1/5) type interface { ( [, ...]) ( [, ...]) ( [, ...]]]) } • • Golang 23
  • 24. (2/5) func main() { var r geometry = &rect{width: 3, height: 4} fmt.Println(r.area()) } type geometry interface { area() float64 } type rect struct { width, height float64 } func (r rect) area() float64 { return r.width * r.height } var _ geometry = (*rect)(nil) // TIPS 24
  • 25. (3/5) interface{} func main() { f("string") // string f(100) // 100 f(true) // true } func f(x interface{}){ fmt.Println(x) } Golang interface{} 25
  • 26. (4/5) : seka/mutexmaps: a utility mutex maps for Golang. type StringMutexMap struct { m *mutexmap.MutexMap } func newStringMutexMap() *StringMutexMap { return &StringMutexMap{mutexmap.New(0)} } func (s *StringMutexMap) Get(key string) string { item := s.m.Get(key) return item.(string) // interface{} string } func (s *StringMutexMap) Put(key string, item string) { s.m.Put(key, item) // string put } 26
  • 27. (4/5) interface{} func main() { var i interface{} = "hello" s := i.(string) fmt.Println(s) // hello f, ok := i.(float64) fmt.Println(f, ok) // 0, false switch t := i.(type) { case string: fmt.Println("string: ", i) // string: hello default: panic() } } 27
  • 28. Golang (extends) (embedding) type Model struct { db database.Database } func NewModel(db database.Database) *Model { return &Model{ db: db, } } func (m *Model) Save(userID, msg string) error { query := `INSERT INTO messages(user_id, message) VALUES (?, ?)` _, err := m.db.Execute(query, userID, msg) return err } 28
  • 29. Golang (1/3) go func([ , ...]) { }( ) go ([ , ...]) Golang goroutine goroutine Golang 29
  • 30. Golang (2/3) ch := make(chan , ) ch <- // ch := <-ch // ch close(ch) // goroutine channel Message-passing make • : 0 • : chan <- <- 30
  • 31. Golang (3/3) seka/bbs-sample goroutine goroutine <-sigs os func (m *Main) createSignalHandler() (context.Context, context.CancelFunc) { sigs := make(chan os.Signal) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) ctx, cancel := context.WithCancel(context.Background()) go func() { s := <-sigs m.logger.Info("Got signal", "sigs", s) cancel() }() return ctx, cancel } 31
  • 32. select select { case msg := <-ch2: fmt.Println("received", msg) case <-ch2: fmt.Println("received") } select ( ) 32