๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Data Base/Go

[์‰ฝ๊ณ  ๋น ๋ฅธ Go ์‹œ์ž‘ํ•˜๊ธฐ] #1.4 Functions part Two

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 10. 26.
๋ฐ˜์‘ํ˜•

[์ถœ์ฒ˜ - Nomad Coders]

 

 

naked return

function์˜ ๋˜ ๋‹ค๋ฅธ ๋ฉ‹์ง„ ๋ถ€๋ถ„์€

'naked' return ์ด๋ผ ๋ถˆ๋ฆฌ๋Š” function ์ด๋‹ค.

 

package main

import (
  "fmt"
  "strings"
)

func lenAndUpper(name string) (length int, uppercase string) {
  length = len(name)
  uppercase = strings.ToUpper(name)
  return  // naked return
}

func main() {
  totalLength, up := lenAndUpper("nico")
  fmt.Println(totalLength, up)
}

์—ฌ๊ธฐ์„œ๋Š” Go๊ฐ€ ์ž๋™์ ์œผ๋กœ (length int, uppercase string) ์–˜๋„ค๋“ค์„ return ํ•  ๊ฑฐ๋ผ๊ณ  ์•Œ์•„ ๋“ฃ๋Š”๋‹ค.

variable์˜ ์ด๋ฆ„์€ ๊ฐ™์•„์•ผ ํ•œ๋‹ค.

 

 

return length, uppercase

์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ•ด๋„ ์ž˜ ์ž‘๋™๋œ๋‹ค. ํ•˜์ง€๋งŒ ๊ตณ์ด ๊ทธ๋Ÿด ํ•„์š”๊ฐ€ ์—†๋‹ค๋Š” ๋œป์ด๋‹ค.

 

 

 

 

defer

defer์€ function์ด ๊ฐ’์„ return ํ•˜๊ณ  ๋‚˜๋ฉด ์‹คํ–‰๋˜๋Š” ๊ฒƒ์ด๋‹ค.

package main

import (
  "fmt"
  "strings"
)

func lenAndUpper(name string) (length int, uppercase string) {
  defer fmt.Println("I'm done") // function์ด ๊ฐ’์„ return ํ•˜๊ณ  ๋‚˜๋ฉด ์‹คํ–‰ ๋  ๊ฒƒ์ด๋‹ค.
  length = len(name)
  uppercase = strings.ToUpper(name)
  return
}

func main() {
  totalLength, up := lenAndUpper("nico")
  fmt.Println(totalLength, up)
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€