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]
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)
}