Package 만들기
패키지를 만들려면 폴더를 만들고, 그 안에 go 파일을 만든다.
패키지 이름을 선언하고, 구현체를 만든다.
main.go에서 해당 패키지를 부를 때는 import에 경로를 지정해준다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| package samplePackage
import "fmt"
func sayHello(){ fmt.Println("Hello!") }
func SayBye(){ fmt.Println("Bye!") }
package main
import ( "fmt"
"github.com/changh95/go-tutorial/samplePackage" )
func main() { fmt.Println("Hello, Go World!") samplePackage.SayBye() }
|
Public / Private 함수
Public 함수는 대문자로 시작한다.
Private 함수는 소문자로 시작한다.
변수
Go 는 Typed language이다.
아래와 같은 타입을 사용할 수 있다.
- bool
- int8, uint8, int16, uint16, int32, uint32, int64, uint64, int, uint, uintptr
- float32, float64.
- complex64, complex128.
- string
const와 non-const도 존재한다. const는 const
로 시작하고, non-const는 var
로 시작한다.
var
의 또다른 표기법으로는 :=
가 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package main
import ( "fmt" )
func main() { const str_const string = "Const" var str_non_const string = "non-const" str_non_const2 := "non-const2"
fmt.Println(str_const) fmt.Println(str_non_const) fmt.Println(str_non_const2) }
|
함수
Go의 함수는 아래와 같이 생겼다.
func
키워드로 시작하며, arguments마다 type을 작성하고 return type도 작성한다.
Multiple returns가 가능하다. Multiple returns에서 어떤 return 값을 무시하려면 _
를 사용하면 된다.
Variadic argument를 받고 싶으면 input argument type으로 ...type
을 사용하면 된다.
Naked return도 가능하다.
defer라는 기능도 있다. 이 기능은 함수가 return하고 난 후에 작동하는 기능을 정의하는 것이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package main
import ( "fmt" "strings" )
func multiply(a int, b int) int { return a * b }
func lenAndUpper(str string) (int, string) { return len(str), strings.ToUpper(str) }
func lenAndUpperNakedReturn(str string) (length int, upper_case string){ length = len(str) upper_case = strings.ToUpper(str) return }
func lenAndUpperNakedReturnWithDefer(str string) (length int, upper_case string){ defer fmt.Println("I'm' done")
length = len(str) upper_case = strings.ToUpper(str) return }
func repeatMe(str ...string) { fmt.Println(str) }
func main() { a := 2 b := 3
answer := multiply(a, b) fmt.Println(answer)
str := "Hello" len, strUpper := lenAndUpper(str) fmt.Println(len, strUpper)
len2, _ := lenAndUpper(str) fmt.Println(len2)
repeatMe("Hi", "Hello", "Bye") }
|