[Go] Comment, Types, Constants, Variables, Functions, defer

이한슬·2023년 12월 30일

Go

목록 보기
3/5

Comment

한 줄 주석을 작성할 때는 //을 사용하고
여러 줄을 작성할 때는 /* */를 사용하면 된다.

Types

bool

string

int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr

byte // alias for uint8

rune // alias for int32
     // represents a Unicode code point

float32 float64

complex64 complex128

Go의 공식 문서를 살펴보면 Go의 기본 타입들은 이렇게 있다고 한다.

Constants

Go에서 상수를 선언하고자 할 때는 다음과 같이 'const {상수명} {type}'의 형태로 선언해주면 된다.

const word string = "hello"

Variables

변수를 선언할 때는 'var {변수명} {type}'의 형태로 선언한다.

var word string = "hello"

또는, func 안에서 선언하는 것이라면 이렇게 선언할 수도 있다.

word := "hello"

이 경우에는 Go가 타입을 알아서 찾아주게 된다. Go가 "hello"를 읽고 string 타입으로 word를 지정해주게 된다. 이렇게 정해진 타입은 내가 다시 임의로 수정할 수 없다. 즉, 이제 word에는 string 타입만 저장할 수 있는 것이다.

Functions

함수를 작성할 때는 func와 함수 이름을 적어주면 된다.

func main(){
// 함수 내용
}

함수에서 파라미터들도 각각 뒤에 타입을 명시해주어야 하며, 이어서 리턴할 타입도 명시해 주어야 한다.

func mul(a int, b int) int {
  return a * b
}

이렇게 조금 더 간단하게 바꾸면 a와 b 모두 int로 인식하게 된다.

func mul(a, b int) int {
  return a * b
}

return 할 필요가 없는 함수라면 타입을 적지 않으면 된다.

func mul2(a int, b int) {
  fmt.Println("hi")
}

다른 언어들에서는 불가능하지만, Go에서는 가능한 것이 있다.
Go는 여러개를 리턴할 수 있다.
여러개를 리턴할 때는 ()안에 순서대로 리턴하는 타입을 적어주면 된다.

func mul3(a int, b int) (int, string) {
  result := a * b
  word := "hello"
  return result, word
}

또는 이런식으로 return 할 수도 있다.

func mul3(a int, b int) (result int, word string) {
  result := a * b
  word := "hello"
  return
}

이렇게 여러개를 리턴하는 함수를 호출할 때는 리턴된 모든 값들을 저장해주어야 한다.

func main(){
	result, word := mul3(2, 3)
}

만약 result만 필요하다고 하면 이렇게 word는 굳이 저장하지 않을 수 있다.

func main(){
	result, _ := mul3(2, 3)
}

내가 원하는 만큼 인자로 전달하기 위해서는 파라미터 타입 앞에 ...을 붙여준다.

func hello(words ...string) {
	fmt.Println(words)
}

func main() {
	hello("hello1", "hello2", "hello3", "hello4")
}

defer

defer 키워드가 붙은 코드는 코드가 있는 함수의 모든 실행이 마치고 나서 마지막에 실행된다.

func mul3(a int, b int) (int, string) {
  defer fmt.Println("1")
  result := a * b
  word := "hello"
  fmt.Println("2")
  return result, word
}

func main(){
   result, _ := mul3(2,3)
   println(result)
}

Result

2
1
6

mul3 함수를 호출하게 되면
(1) 2가 먼저 출력되고
(2) result와 word가 리턴이 된 후
(3) defer의 1이 출력되고
(4) main 함수의 result가 출력된다

profile
궁금하면 일단 먹어보는 소프트웨어 전공생

0개의 댓글