본문 바로가기

SW LAB/Go Lang

[Google Go 언어] 기본 문법

func

// 배열 인자 받는 법
func receiveStringArray(word ...string) {
	
}
// 인자 타입 생략
func summaryParamType(a, b int) int {
	return a * b
}
// defer 사용과 다중 데이터 반환
func deferFunction(name stirng) (int, string) {
	defer fmt.Println("After call")
	return len(name), strings.ToUpper(name)
}

for

func superAdd(numbers ...int) int {
	total := 0
	for _, number := range numbers {
		total += number
	}
	for i := 0; i < len(numbers); i++ {
		fmt.Println(numbers[i])
	}
	return total
}

if

func canIDrink(age int) bool {
	if koreanAge := age + 2; koreanAge < 18 {
		return false
	} else {
		return true
	}
}

switch

func canIClub(age int) bool {
	switch age {
	case 10:
		return false
	case 18:
		return true
	}
	switch {
	case age < 18:
		return false
	case age == 18:
		return true
	case age > 50:
		return false
	}
	switch koreanAge := age + 2; koreanAge {
	case 10:
		return false
	case 18:
		return true
	}
	return false
}

pointers

func main() {
	a := 2
	b := a
	a = 10
	fmt.Println(a, b)   // 10, 2
	fmt.Println(&a, &b) // 0xc000012088 0xc0000120a0
	c := &a
	a = 15
	fmt.Println(a, c)  // 15 0xc000012088
	fmt.Println(a, *c) // 15 15
	*c = 20
	fmt.Println(a) // 20
}

Arrays and Slices

func main() {
	names := [5]string{"nico", "lynn", "dal"}
	names[3] = "alala"
	names[4] = "bcbcb"
	fmt.Println(names)

	// slice
	nameSlice := []string{"nico", "lynn", "dal"}
	// nameSlice[3] = "flynn" // 오류 발생 (index 초과)
	nameSlice = append(nameSlice, "flynn")
	fmt.Println(nameSlice)
}

Maps

func main() {
	nico := map[string]string{"name": "nico", "age": "12"}
	fmt.Println(nico)
	for key, value := range nico {
		fmt.Println(key, value)
	}
}

Structs

type persion struct {
	name    string
	age     int
	favFood []string
}

func main() {
	favFood := []string{"kimchi", "ramen"}
	nico := persion{"nico", 18, favFood}
	fmt.Println(nico)      // {nico 18 [kimchi ramen]}
	fmt.Println(nico.name) // nico

	jhon := persion{name: "jhon", age: 19, favFood: favFood}
	fmt.Println(jhon) // {jhon 19 [kimchi ramen]}
}