21
golang tour [email protected] / 전수현

Let's golang

  • Upload
    -

  • View
    430

  • Download
    9

Embed Size (px)

Citation preview

Page 1: Let's golang

golang [email protected] / 전수현

Page 2: Let's golang

golang history● 2009년 11월 발표● 구글 엔지니어들에 의해 개발 ● 최신 안정된 릴리즈(stable) 버전 1.3.3 ● 영향을 받은 언어 : C, Limbo, Modula, Newsqueak, Oberon, 파스칼● 문법 : C와 비슷● 정적 타입 컴파일 언어의 효율성과 동적 언어처럼 쉬운 프로그래밍을 할 수 있도록 하는 것을 목표로 한 가비지 컬렉션 기능이 있는 컴파일, 병행성(concurrent) 프로그래밍 언어

● 목적○ 안전성: 타입 안전성과 메모리 안전성○ 병행성과 통신을 위한 훌륭한 지원○ 효과적인 가비지 컬렉션○ 빠른 컴파일

Page 3: Let's golang

Getting started● download

○ http://golang.org/dl/

● setting .bash_profile ○ $GOROOT

■ set {golang home path}○ $GOPATH

■ set {golang source code path}

Page 4: Let's golang

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

Page 5: Let's golang

Hello worldpackage main

import "fmt"

func main() { fmt.Println("hello world")}

$ go run hello-world.gohello world

$ go build hello-world.go // output binary$ lshello-world hello-world.go

$ ./hello-worldhello world

Page 6: Let's golang

Variablespackage 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)

$ go run variables.goinitial1 2true

Page 7: Let's golang

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

$ go run variables.go0short

Page 8: Let's golang

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.go123789loop

Page 9: Let's golang

If / Elsepackage 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 odd8 is divisible by 49 has 1 digit

Page 10: Let's golang

Arrayspackage mainimport "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.goemp: [0 0 0 0 0]set: [0 0 0 0 100]get: 100len: 5dcl: [1 2 3 4 5]2d: [[0 1 2] [1 2 3]]

Page 11: Let's golang

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.goemp: [ ]set: [a b c]get: clen: 3apd: [a b c d e f]

Page 12: Let's golang

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.gocpy: [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]]

Page 13: Let's golang

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.godcl: [g h i]2d: [[0] [1 2] [2 3 4]]

Page 14: Let's golang

Slices internalsOur variable s, created earlier by make([]byte, 5), is structured like this:

The length is the number

Page 15: Let's golang

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: 7len: 2

Page 16: Let's golang

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.gomap: map[k1:7]prs: falsemap: map[foo:1 bar:2]

Page 17: Let's golang

Deferpackage 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.gocreatingwritingclosing

func writeFile(f *os.File) { fmt.Println("writing") fmt.Fprintln(f, "data")

}

func closeFile(f *os.File) { fmt.Println("closing") f.Close()}

Page 18: Let's golang

Deferpackage 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.gocreatingwritingclosing

어떤 경로의 함수가 값을 리턴하는지에 관계없이 자원을 해제해야만하는 상황을 다루기 위해서는 효과적인 방법. 전형적인 예로 mutex를 해제하거나 file을 닫는 경우다.

Page 19: Let's golang

Java vs golang

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

모든 짝수번째 숫자를 * 로 치환하시오.(홀수번째 숫자,또는 짝수번째 문자를 치환하면 안됩니다.)

Example: a1b2cde3~g45hi6 → a*b*cde*~g4*hi6

java go

Page 21: Let's golang

감사합니다