[Golang] 명령줄에 대한 플래그 얻기(Command-Line Flag)

Go에서 만들어진 실행 파일을 실행할 때, 명령줄에 입력한 플래그 값을 쉽게 얻기 위해 제공하는 flag 패키지 사용에 대한 코드를 정리해 봅니다. 아래의 코드는 플래그로써 word, numb, fork에 값을 지정하고자 하는 경우입니다. word는 문자열, numb는 정수형, fork는 블린형으로 지정합니다.

package main

import (
    "flag"
    "fmt"
)

func main() {
    wordPtr := flag.String("word", "foo", "a string")
    numPtr := flag.Int("numb", 42, "an int")
    boolPtr := flag.Bool("fork", false, "a bool")

    flag.Parse()

    fmt.Println("word: ", *wordPtr)
    fmt.Println("numb: ", *numPtr)
    fmt.Println("fork: ", *boolPtr)
    fmt.Println("tail: ", flag.Args())
}

위의 프로그램을 컴파일해 실행 파일로 cmd_flag.exe가 만들어졌다고 할 때, 앞서 언급한 각 플래그에 값을 지정하여 실행한 예는 아래와 같습니다.

d:\__Working__\tstGo\cmd_flags>cmd_flags.exe -word=Hello -numb=23 -fork=true
word:  Hello
numb:  23
fork:  true
tail:  []

d:\__Working__\tstGo\cmd_flags>cmd_flags.exe -word="Hello World" -numb=23 -fork=true
word:  Hello World
numb:  23
fork:  true
tail:  []

d:\__Working__\tstGo\cmd_flags>cmd_flags.exe -word="Hello World" -numb=23 -fork=true a1 a2 a3
word:  Hello World
numb:  23
fork:  true
tail:  [a1 a2 a3]

d:\__Working__\tstGo\cmd_flags>cmd_flags.exe -word="Hello World" -numb=a -fork=true
invalid value "a" for flag -numb: strconv.ParseInt: parsing "a": invalid syntax
Usage of cmd_flags.exe:
  -fork
        a bool
  -numb int
        an int (default 42)
  -word string
        a string (default "foo")

d:\__Working__\tstGo\cmd_flags>

[Golang] 클로져, 가변인자 예제코드

closures

상태값을 가지는 함수를 반환하는 함수에 대한 예입니다. (출처: https://gobyexample.com)

package main

import (
    "fmt"
)

func intSeq() func() int {
    i := 0

    return func() int {
        i += 1
        return i
    }
}

func main() {
    nextInt1 := intSeq()
    nextInt2 := intSeq()

    fmt.Println(nextInt1())
    fmt.Println(nextInt1())
    fmt.Println(nextInt1())
    fmt.Println(nextInt1())

    fmt.Println(nextInt2())
    fmt.Println(nextInt2())
    fmt.Println(nextInt2())
    fmt.Println(nextInt2())
}

결과는 아래와 같습니다.

1
2
3
4
1
2
3
4

가변인자(Variadic)

함수에 임의 개수의 인자를 넘길 수 있는 가변인자를 갖는 함수에 대한 예입니다. 특히 네번째 sum 함수의 호출시 인자를 슬라이스로 전달 가능합니다. (출처: https://gobyexample.com)

package main

import (
    "fmt"
)

func sum(nums ...int) {
    fmt.Print(nums, " ")
    total := 0

    for _, num := range nums {
        total += num
    }

    fmt.Println(total)
}

func main() {
    sum(1, 2)
    sum(1, 2, 3)
    sum(1, 2, 3, 4)

    nums := []int{1, 2, 3, 4}
    sum(nums...)
}

결과는 아래와 같습니다.

[1 2] 3
[1 2 3] 6
[1 2 3 4] 10
[1 2 3 4] 10