SlideShare a Scribd company logo
1 of 21
Download to read offline
golang tour 
suhyunjun@gmail.com / 전수현
golang history 
● 2009년 11월 발표 
● 구글 엔지니어들에 의해 개발 
● 최신 안정된 릴리즈(stable) 버전 1.3.3 
● 영향을 받은 언어 : C, Limbo, Modula, Newsqueak, Oberon, 파스칼 
● 문법 : C와 비슷 
● 정적 타입 컴파일 언어의 효율성과 동적 언어처럼 쉬운 프로그래밍을 할 수 있도록 하는 것 
을 목표로 한 가비지 컬렉션 기능이 있는 컴파일, 병행성(concurrent) 프로그래밍 언어 
● 목적 
○ 안전성: 타입 안전성과 메모리 안전성 
○ 병행성과 통신을 위한 훌륭한 지원 
○ 효과적인 가비지 컬렉션 
○ 빠른 컴파일
Getting started 
● download 
○ http://golang.org/dl/ 
● setting .bash_profile 
○ $GOROOT 
■ set {golang home path} 
○ $GOPATH 
■ set {golang source code path}
Data types 
● Boolean types, String types, Array types, Map types 
● Numeric types 
○ uint8 the set of all unsigned 8-bit integers (0 to 255) 
○ uint16 the set of all unsigned 16-bit integers (0 to 65535) 
○ uint32 the set of all unsigned 32-bit integers (0 to 4294967295) 
○ uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615) 
○ int8 the set of all signed 8-bit integers (-128 to 127) 
○ int16 the set of all signed 16-bit integers (-32768 to 32767) 
○ int32 the set of all signed 32-bit integers (-2147483648 to 2147483647) 
○ int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807) 
○ float32 the set of all IEEE-754 32-bit floating-point numbers 
○ float64 the set of all IEEE-754 64-bit floating-point numbers 
○ complex64 the set of all complex numbers with float32 real and imaginary parts 
○ complex128 the set of all complex numbers with float64 real and imaginary parts 
○ byte alias for uint8 
○ rune alias for int32
Hello world 
package main 
import "fmt" 
func main() { 
fmt.Println("hello world") 
} 
$ go run hello-world.go 
hello world 
$ go build hello-world.go // output binary 
$ ls 
hello-world hello-world.go 
$ ./hello-world 
hello world
Variables 
package main 
import "fmt" 
func main() { 
var a string = "initial" // `var` declares 1 or more variables. 
fmt.Println(a) 
var b, c int = 1, 2 // You can declare multiple variables at once. 
fmt.Println(b, c) 
var d = true // Go will infer the type of initialized variables. 
fmt.Println(d) 
……. (next) 
i$1n 2gitoia rlun variables.go true
Variables 
package main 
import "fmt" 
func main() { 
….. 
// Variables declared without a corresponding 
// initialization are _zero-valued_. For example, the 
// zero value for an `int` is `0`. 
var e int 
fmt.Println(e) 
// The `:=` syntax is shorthand for declaring and 
// initializing a variable, e.g. for 
// `var f string = "short"` in this case. 
f := "short" 
fmt.Println(f) 
} 
s$0h goor trun variables.go
For (initial/condition/after) 
package main 
import "fmt" 
func main() { 
i := 1 
for i <= 3 { 
fmt.Println(i) 
i = i + 1 
} 
for j := 7; j <= 9; j++ { 
fmt.Println(j) 
} 
for { 
fmt.Println("loop") 
break 
} 
} 
$ go run for.go 
123789 
loop
If / Else 
package main 
import "fmt" 
func main() { 
if 7%2 == 0 { 
fmt.Println("7 is even") 
} else { 
fmt.Println("7 is odd") 
} 
if 8%4 == 0 { 
fmt.Println("8 is divisible by 4") 
} 
if num := 9; num < 0 { 
fmt.Println(num, "is negative") 
} else if num < 10 { 
fmt.Println(num, "has 1 digit") 
} else { 
fmt.Println(num, "has multiple digits") 
} 
} 
$ go run if-else.go 
7 is odd 
8 is divisible by 4 
9 has 1 digit
Arrays 
package main 
import "fmt" 
func main() { 
var a [5]int 
fmt.Println("emp:", a) 
a[4] = 100 
fmt.Println("set:", a) 
fmt.Println("get:", a[4]) 
fmt.Println("len:", len(a)) 
b := [5]int{1, 2, 3, 4, 5} 
fmt.Println("dcl:", b) 
var twoD [2][3]int 
for i := 0; i < 2; i++ { 
for j := 0; j < 3; j++ { 
twoD[i][j] = i + j 
} 
} 
fmt.Println("2d: ", twoD) 
} 
$ go run arrays.go 
emp: [0 0 0 0 0] 
set: [0 0 0 0 100] 
get: 100 
len: 5 
dcl: [1 2 3 4 5] 
2d: [[0 1 2] [1 2 3]]
Slices (array 보다 많이 사용) 
package main 
import "fmt" 
func main() { 
s := make([]string, 3) 
fmt.Println("emp:", s) 
s[0] = "a" 
s[1] = "b" 
s[2] = "c" 
fmt.Println("set:", s) 
fmt.Println("get:", s[2]) 
fmt.Println("len:", len(s)) 
s = append(s, "d") 
s = append(s, "e", "f") 
fmt.Println("apd:", s) 
…. (next) 
$ go run slices.go 
emp: [ ] 
set: [a b c] 
get: c 
len: 3 
apd: [a b c d e f]
Slices (slice[low:high]) 
package main 
import "fmt" 
func main() { 
… 
c := make([]string, len(s)) 
copy(c, s) 
fmt.Println("cpy:", c) 
l := s[2:5] //elements s[2], s[3], and s[4] 
fmt.Println("sl1:", l) 
l = s[:5] //This slices up to (but excluding) s[5] 
fmt.Println("sl2:", l) 
l = s[2:] //This slices up from (and including) s[2] 
fmt.Println("sl3:", l) 
… (next) 
$ go run slices.go 
cpy: [a b c d e f] 
sl1: [c d e] 
sl2: [a b c d e] 
sl3: [c d e f] 
dcl: [g h i] 
2d: [[0] [1 2] [2 3 4]]
Slices (array 보다 많이 사용) 
package main 
import "fmt" 
func main() { 
… 
t := []string{"g", "h", "i"} 
fmt.Println("dcl:", t) 
twoD := make([][]int, 3) 
for i := 0; i < 3; i++ { 
innerLen := i + 1 
twoD[i] = make([]int, innerLen) 
for j := 0; j < innerLen; j++ { 
twoD[i][j] = i + j 
} 
} 
fmt.Println("2d: ", twoD) 
} 
$ go run slices.go 
dcl: [g h i] 
2d: [[0] [1 2] [2 3 4]]
Slices internals 
Our variable s, created earlier by make([]byte, 5), is structured like this: 
The length is the number
Maps make(map[key-type]val-type) (다른 언어 : hashes 나 dicts로 불리움) 
package main 
import "fmt" 
func main() { 
m := make(map[string]int) 
m["k1"] = 7 
m["k2"] = 13 
fmt.Println("map:", m) 
v1 := m["k1"] 
fmt.Println("v1: ", v1) 
fmt.Println("len:", len(m)) 
… (next) 
} 
$ go run maps.go 
map: map[k1:7 k2:13] 
v1: 7 
len: 2
Maps make(map[key-type]val-type) (다른 언어 : hashes 나 dicts로 불리움) 
package main 
import "fmt" 
func main() { 
… 
delete(m, "k2") 
fmt.Println("map:", m) 
_, prs := m["k2"] 
fmt.Println("prs:", prs) 
n := map[string]int{"foo": 1, "bar": 2} 
fmt.Println("map:", n) 
} 
$ go run slices.go 
map: map[k1:7] 
prs: false 
map: map[foo:1 bar:2]
Defer 
package main 
import "fmt" 
import "os" 
func main() { 
f := createFile("/tmp/defer.txt") 
defer closeFile(f) 
writeFile(f) 
} 
func createFile(p string) *os.File { 
fmt.Println("creating") 
f, err := os.Create(p) 
if err != nil { 
panic(err) 
} 
return f 
} 
… (next) 
$ go run defer.go 
creating 
writing 
closing 
… 
func writeFile(f *os.File) { 
fmt.Println("writing") 
fmt.Fprintln(f, "data") 
} 
func closeFile(f *os.File) { 
fmt.Println("closing") 
f.Close() 
}
Defer 
package main 
import "fmt" 
import "os" 
.... 
func writeFile(f *os.File) { 
fmt.Println("writing") 
fmt.Fprintln(f, "data") 
} 
func closeFile(f *os.File) { 
fmt.Println("closing") 
f.Close() 
} 
$ go run defer.go 
creating 
writing 
closing 
어떤 경로의 함수가 값을 리턴하는지에 관계없이 자원을 해제해 
야만하는 상황을 다루기 위해서는 효과적인 방법. 전형적인 예로 
mutex를 해제하거나 file을 닫는 경우다.
Java vs golang 
모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.) 
Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6 
java go 
public static void main(String args[]){ 
String text = "a1b2cde3~g45hi6"; 
String replace = ""; 
for(int i=0; i<text.length();i++){ 
char charAt = text.charAt(i); 
if(i % 2 != 0 && Character.isDigit(charAt)){ 
charAt = '*'; 
} 
replace += charAt; 
} 
System.out.print(replace); 
} 
func main() { 
str := "a1b2cde3~g45hi6" 
for index, runeValue := range str { 
if unicode.IsDigit(runeValue) && index % 2 != 0 { 
str = strings.Replace(str, string(runeValue), "*", -1) 
} 
} 
fmt.Printf(str) 
}
참고자료 
● http://en.wikipedia.org/wiki/Go_(programming_language) 
● https://golang.org/doc/go1.3 
● https://gobyexample.com/ 
● http://golang.org/ref/spec#Method_sets 
● https://code.google.com/p/golang-korea/wiki/EffectiveGo 
● http://blog.golang.org/go-slices-usage-and-internals
감사합니다

More Related Content

What's hot

All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
10〜30分で何となく分かるGo
10〜30分で何となく分かるGo10〜30分で何となく分かるGo
10〜30分で何となく分かるGo
Moriyoshi Koizumi
 
โปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐานโปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐาน
knang
 
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!..."A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
akaptur
 

What's hot (20)

All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
Implementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & CImplementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & C
 
10〜30分で何となく分かるGo
10〜30分で何となく分かるGo10〜30分で何となく分かるGo
10〜30分で何となく分かるGo
 
Py3k
Py3kPy3k
Py3k
 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
 
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's PerspectiveThe Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
 
Golang勉強会
Golang勉強会Golang勉強会
Golang勉強会
 
โปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐานโปรแกรมย่อยและฟังชันก์มาตรฐาน
โปรแกรมย่อยและฟังชันก์มาตรฐาน
 
dplyr
dplyrdplyr
dplyr
 
Python 3
Python 3Python 3
Python 3
 
Clang2018 class3
Clang2018 class3Clang2018 class3
Clang2018 class3
 
Data structures
Data structuresData structures
Data structures
 
Encrypt all transports
Encrypt all transportsEncrypt all transports
Encrypt all transports
 
Introduction to F# for the C# developer
Introduction to F# for the C# developerIntroduction to F# for the C# developer
Introduction to F# for the C# developer
 
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!..."A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
 

Similar to Let's golang

โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
Little Tukta Lita
 

Similar to Let's golang (20)

Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programming
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 
Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
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
 
About Go
About GoAbout Go
About Go
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with go
 
Assignment6
Assignment6Assignment6
Assignment6
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
โปรแกรมย่อยและฟังชั่นมาตรฐาน ม.6 1
 
Burrowing through go! the book
Burrowing through go! the bookBurrowing through go! the book
Burrowing through go! the book
 
III MCS python lab (1).pdf
III MCS python lab (1).pdfIII MCS python lab (1).pdf
III MCS python lab (1).pdf
 
Python crush course
Python crush coursePython crush course
Python crush course
 
JavaForum Nord 2021: Java to Go - Google Go für Java-Entwickler
JavaForum Nord 2021: Java to Go - Google Go für Java-EntwicklerJavaForum Nord 2021: Java to Go - Google Go für Java-Entwickler
JavaForum Nord 2021: Java to Go - Google Go für Java-Entwickler
 
03 Geographic scripting in uDig - halfway between user and developer
03 Geographic scripting in uDig - halfway between user and developer03 Geographic scripting in uDig - halfway between user and developer
03 Geographic scripting in uDig - halfway between user and developer
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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?
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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, ...
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 

Let's golang

  • 2. golang history ● 2009년 11월 발표 ● 구글 엔지니어들에 의해 개발 ● 최신 안정된 릴리즈(stable) 버전 1.3.3 ● 영향을 받은 언어 : C, Limbo, Modula, Newsqueak, Oberon, 파스칼 ● 문법 : C와 비슷 ● 정적 타입 컴파일 언어의 효율성과 동적 언어처럼 쉬운 프로그래밍을 할 수 있도록 하는 것 을 목표로 한 가비지 컬렉션 기능이 있는 컴파일, 병행성(concurrent) 프로그래밍 언어 ● 목적 ○ 안전성: 타입 안전성과 메모리 안전성 ○ 병행성과 통신을 위한 훌륭한 지원 ○ 효과적인 가비지 컬렉션 ○ 빠른 컴파일
  • 3. Getting started ● download ○ http://golang.org/dl/ ● setting .bash_profile ○ $GOROOT ■ set {golang home path} ○ $GOPATH ■ set {golang source code path}
  • 4. Data types ● Boolean types, String types, Array types, Map types ● Numeric types ○ uint8 the set of all unsigned 8-bit integers (0 to 255) ○ uint16 the set of all unsigned 16-bit integers (0 to 65535) ○ uint32 the set of all unsigned 32-bit integers (0 to 4294967295) ○ uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615) ○ int8 the set of all signed 8-bit integers (-128 to 127) ○ int16 the set of all signed 16-bit integers (-32768 to 32767) ○ int32 the set of all signed 32-bit integers (-2147483648 to 2147483647) ○ int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807) ○ float32 the set of all IEEE-754 32-bit floating-point numbers ○ float64 the set of all IEEE-754 64-bit floating-point numbers ○ complex64 the set of all complex numbers with float32 real and imaginary parts ○ complex128 the set of all complex numbers with float64 real and imaginary parts ○ byte alias for uint8 ○ rune alias for int32
  • 5. Hello world package main import "fmt" func main() { fmt.Println("hello world") } $ go run hello-world.go hello world $ go build hello-world.go // output binary $ ls hello-world hello-world.go $ ./hello-world hello world
  • 6. Variables package main import "fmt" func main() { var a string = "initial" // `var` declares 1 or more variables. fmt.Println(a) var b, c int = 1, 2 // You can declare multiple variables at once. fmt.Println(b, c) var d = true // Go will infer the type of initialized variables. fmt.Println(d) ……. (next) i$1n 2gitoia rlun variables.go true
  • 7. Variables package main import "fmt" func main() { ….. // Variables declared without a corresponding // initialization are _zero-valued_. For example, the // zero value for an `int` is `0`. var e int fmt.Println(e) // The `:=` syntax is shorthand for declaring and // initializing a variable, e.g. for // `var f string = "short"` in this case. f := "short" fmt.Println(f) } s$0h goor trun variables.go
  • 8. For (initial/condition/after) package main import "fmt" func main() { i := 1 for i <= 3 { fmt.Println(i) i = i + 1 } for j := 7; j <= 9; j++ { fmt.Println(j) } for { fmt.Println("loop") break } } $ go run for.go 123789 loop
  • 9. If / Else package main import "fmt" func main() { if 7%2 == 0 { fmt.Println("7 is even") } else { fmt.Println("7 is odd") } if 8%4 == 0 { fmt.Println("8 is divisible by 4") } if num := 9; num < 0 { fmt.Println(num, "is negative") } else if num < 10 { fmt.Println(num, "has 1 digit") } else { fmt.Println(num, "has multiple digits") } } $ go run if-else.go 7 is odd 8 is divisible by 4 9 has 1 digit
  • 10. Arrays package main import "fmt" func main() { var a [5]int fmt.Println("emp:", a) a[4] = 100 fmt.Println("set:", a) fmt.Println("get:", a[4]) fmt.Println("len:", len(a)) b := [5]int{1, 2, 3, 4, 5} fmt.Println("dcl:", b) var twoD [2][3]int for i := 0; i < 2; i++ { for j := 0; j < 3; j++ { twoD[i][j] = i + j } } fmt.Println("2d: ", twoD) } $ go run arrays.go emp: [0 0 0 0 0] set: [0 0 0 0 100] get: 100 len: 5 dcl: [1 2 3 4 5] 2d: [[0 1 2] [1 2 3]]
  • 11. Slices (array 보다 많이 사용) package main import "fmt" func main() { s := make([]string, 3) fmt.Println("emp:", s) s[0] = "a" s[1] = "b" s[2] = "c" fmt.Println("set:", s) fmt.Println("get:", s[2]) fmt.Println("len:", len(s)) s = append(s, "d") s = append(s, "e", "f") fmt.Println("apd:", s) …. (next) $ go run slices.go emp: [ ] set: [a b c] get: c len: 3 apd: [a b c d e f]
  • 12. Slices (slice[low:high]) package main import "fmt" func main() { … c := make([]string, len(s)) copy(c, s) fmt.Println("cpy:", c) l := s[2:5] //elements s[2], s[3], and s[4] fmt.Println("sl1:", l) l = s[:5] //This slices up to (but excluding) s[5] fmt.Println("sl2:", l) l = s[2:] //This slices up from (and including) s[2] fmt.Println("sl3:", l) … (next) $ go run slices.go cpy: [a b c d e f] sl1: [c d e] sl2: [a b c d e] sl3: [c d e f] dcl: [g h i] 2d: [[0] [1 2] [2 3 4]]
  • 13. Slices (array 보다 많이 사용) package main import "fmt" func main() { … t := []string{"g", "h", "i"} fmt.Println("dcl:", t) twoD := make([][]int, 3) for i := 0; i < 3; i++ { innerLen := i + 1 twoD[i] = make([]int, innerLen) for j := 0; j < innerLen; j++ { twoD[i][j] = i + j } } fmt.Println("2d: ", twoD) } $ go run slices.go dcl: [g h i] 2d: [[0] [1 2] [2 3 4]]
  • 14. Slices internals Our variable s, created earlier by make([]byte, 5), is structured like this: The length is the number
  • 15. Maps make(map[key-type]val-type) (다른 언어 : hashes 나 dicts로 불리움) package main import "fmt" func main() { m := make(map[string]int) m["k1"] = 7 m["k2"] = 13 fmt.Println("map:", m) v1 := m["k1"] fmt.Println("v1: ", v1) fmt.Println("len:", len(m)) … (next) } $ go run maps.go map: map[k1:7 k2:13] v1: 7 len: 2
  • 16. Maps make(map[key-type]val-type) (다른 언어 : hashes 나 dicts로 불리움) package main import "fmt" func main() { … delete(m, "k2") fmt.Println("map:", m) _, prs := m["k2"] fmt.Println("prs:", prs) n := map[string]int{"foo": 1, "bar": 2} fmt.Println("map:", n) } $ go run slices.go map: map[k1:7] prs: false map: map[foo:1 bar:2]
  • 17. Defer package main import "fmt" import "os" func main() { f := createFile("/tmp/defer.txt") defer closeFile(f) writeFile(f) } func createFile(p string) *os.File { fmt.Println("creating") f, err := os.Create(p) if err != nil { panic(err) } return f } … (next) $ go run defer.go creating writing closing … func writeFile(f *os.File) { fmt.Println("writing") fmt.Fprintln(f, "data") } func closeFile(f *os.File) { fmt.Println("closing") f.Close() }
  • 18. Defer package main import "fmt" import "os" .... func writeFile(f *os.File) { fmt.Println("writing") fmt.Fprintln(f, "data") } func closeFile(f *os.File) { fmt.Println("closing") f.Close() } $ go run defer.go creating writing closing 어떤 경로의 함수가 값을 리턴하는지에 관계없이 자원을 해제해 야만하는 상황을 다루기 위해서는 효과적인 방법. 전형적인 예로 mutex를 해제하거나 file을 닫는 경우다.
  • 19. Java vs golang 모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.) Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6 java go public static void main(String args[]){ String text = "a1b2cde3~g45hi6"; String replace = ""; for(int i=0; i<text.length();i++){ char charAt = text.charAt(i); if(i % 2 != 0 && Character.isDigit(charAt)){ charAt = '*'; } replace += charAt; } System.out.print(replace); } func main() { str := "a1b2cde3~g45hi6" for index, runeValue := range str { if unicode.IsDigit(runeValue) && index % 2 != 0 { str = strings.Replace(str, string(runeValue), "*", -1) } } fmt.Printf(str) }
  • 20. 참고자료 ● http://en.wikipedia.org/wiki/Go_(programming_language) ● https://golang.org/doc/go1.3 ● https://gobyexample.com/ ● http://golang.org/ref/spec#Method_sets ● https://code.google.com/p/golang-korea/wiki/EffectiveGo ● http://blog.golang.org/go-slices-usage-and-internals