Functions
Go์ functions๋ฅผ ์์๋ณด์์
Types in fuction
ํจ์์ argument์ return ๊ฐ์ type์ ๋ช ์ํด์ค์ผ ํ๋ค
compiler์๊ฒ type์ด ๋ฌด์์ธ์ง ์๋ ค์ค์ผ๋ก์จ ๋น ๋ฅด๊ฒ compile ํ ์ ์๊ฒ ํ๋ค!
Java๋ ์ ์ฌ! Python์ด๋์ ๋๋ฌด ๋ค๋ฆ...
ex)
package main import "fmt" func multiply(a int, b int) int { return a * b } func main() { fmt.Println(multiply(2, 4)) }
argument ๋ค์ type์ด ๊ฐ์ผ๋ฉด ํ ๋ฒ๋ง ๋ช ์ํด๋ ๋๋ค
ex)
func multiply(a, b int) int { return a * b }
return์ด ํ์ํ ํจ์๋ ๊ผญ return type์ ๋ช ์ํด์ผ ํ๋ค!
Multiple Return Values
Go๋ multiple return value ๋ฅผ ์ง์ํ๋ค
๋ง์ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด๋ค๊ณผ ๋ค๋ฅธ Go์ ํน์ง์ด๋ค!
ex)
package main import ( "fmt" "strings" ) func lenAndUpper(name string) (int, string) { return len(name), strings.ToUpper(name) } func main() { totalLength, upperName := lenAndUpper("chloe") fmt.Println(totalLength, upperName) }
๋จ, return ํ๋ ๊ฐ์๋ณด๋ค ์ ๊ฒ ๊ฐ์ ๋ฐ์ ์ ์๋ค!
ex) Error๊ฐ ๋ฐ์ํ ์์
totalLength := lenAndUpper("chloe")
lenAndUpper๋ ๋ ๊ฐ์ ๊ฐ์ return ํ๊ธฐ ๋๋ฌธ์ ์๋์ ๊ฐ์ error๋ฅผ ๋ฑ๋๋ค
go101/03_functions on ๎ master [!?] via ๐น v1.15.6 โ go run main.go # command-line-arguments ./main.go:18:14: assignment mismatch: 1 variable but lenAndUpper returns 2 values
์ด๋ด ๋์๋
_
๋ฅผ ๋ฃ์ด value ๊ฐ์ ๋ฌด์ํ๋๋ก ํ๋ฉด ๋๋คex)
totalLength, _ := lenAndUpper("chloe")
์ด๋ ๊ฒ
underscore (_)
๋ ignored value๋ก ์ฌ์ฉํ ์ ์๋ค!compiler๋ ignored value๋ฅผ ๋ง๊ทธ๋๋ก ๋ฌด์ํ๋ค
Variadic functions
...
์ ์ฌ์ฉํ์ฌ ๊ฐ๋ณ์ธ์ ํจ์๋ฅผ ๋ง๋ค ์ ์๋ค๋ฐฉ๋ฒ์ type์์
...
๋ฅผ ๋ถ์ด๋ฉด ๋๋ค! ์ด๊ฒ ๋์ด๋ค!ex)
func repeatMe(words ...string) { fmt.Println(words) }
Naked returns
ํจ์์ return type์ ๋ช ์ํ ๋ returnํ ๊ฐ์ ๋ฏธ๋ฆฌ ์ ์ธํ๊ณ , ๋น์ด์๋ return์ ํ๋ ๊ฒ
์ ์ธ ํ ๋ ์ด๊ธฐํ ๋๋ฏ๋ก ํจ์ ๋ด๋ถ์์๋ ํด๋น variable์ update ํ๋ ๊ฒ์ด๋ค!
returnํ value๋ฅผ ๋ช ์ํ์ง ์๊ณ return ํ ์ ์๋ค
ex)
package main import ( "fmt" "strings" ) func lenAndLower(name string) (length int, lowercase string) { length = len(name) lowercase = strings.ToLower(name) return } func main() { length, name := lenAndLower("CHLOE") fmt.Println(length, name) }
ํ์คํ๊ฒ ์ด๋ค ๊ฐ์ด return ๋๋์ง ๋ช ์ํ๊ณ ์ถ์ผ๋ฉด ์ฌ์ฉํ์ง ์๋ ๊ฒ์ด ์ข๋ค
defer
function์ด ๋๋ ํ ์คํ๋๋ ์ฝ๋
ํจ์๊ฐ ์ข ๋ฃ๋์์ ๋ defer๋ฅผ ํตํด ์ถ๊ฐ์ ์ผ๋ก ๋ฌด์ธ๊ฐ ๋์ํ ์ ์๋๋ก ์ค์ ํ ์ ์๋ค
return ๊ฐ์ด ์๋ ํจ์๋ผ๋ฉด return ๋ ํ์ defer ๊ฐ ์คํ๋๋ค
ex)
func lenAndLower(name string) (length int, lowercase string) { // defer defer fmt.Println("Done!") length = len(name) lowercase = strings.ToLower(name) return }
defer๋ฅผ ํจ์ ์ข ๋ฃ ํ image๋ file์ ๋ซ๊ฑฐ๋ ์ญ์ ํ๊ณ , API request ๋ณด๋ด๋ ๊ฒ์ ํ์ฉํ ์ ์๋ค!
Last updated
Was this helpful?