Arrays

Go의 Array는 다른 언어들과 다르게 크기를 마음대로 조절할 수 있다. 

테스트

func main() {
	names := [5]string{"nico", "qazyj", "dal"}
	fmt.Println(names)
}

 

출력

일반적인 배열을 만드는 방법이다. 배열의 크기를 지정하고 배열안에 값을 넣어준다.

 

Slice

java에서의 List와 같은 느낌이 든다. slice라고 부르는데, append를 이용해서 사용할 수 있다.

배열의 크기를 지정하면 append를 사용할 수 없지만, 크기가 지정되어있지 않다면 append를 사용해서 크기를 마음대로 조절할 수 있다.

테스트

func main() {
	names := []string{"nico", "qazyj", "dal"}
	fmt.Println(names)
}

출력

위와 다르게 추가된 수 만큼 배열의 크기가 생성된다. append를 사용해보자

func main() {
	names := []string{"nico", "qazyj", "dal"}
	names = append(names, "test")
	fmt.Println(names)
}

출력

크기가 1만큼 증가하며 새로운 string이 추가된 것을 확인할 수 있다.

 

그렇다면, append는 어떻게 이루어져 있을까?

// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
// Append returns the updated slice. It is therefore necessary to store the
// result of append, often in the variable holding the slice itself:
//
//	slice = append(slice, elem1, elem2)
//	slice = append(slice, anotherSlice...)
//
// As a special case, it is legal to append a string to a byte slice, like this:
//
//	slice = append([]byte("hello "), "world"...)
func append(slice []Type, elems ...Type) []Type

builtin.go 라는 파일에 append는 위와같이 정의되어 있다. 설명을 보면 1개만 되는 것이 아닌 여러개가 한꺼번에 뒤로 추가해주는 것도 가능하다고 한다. 사용 방법은 배열 변수명 = append(배열 변수명, 추가하고싶은 element.....) 방법으로 사용하면 된다.

 

Java는 배열과 List가 있는 반면, Go의 경우 배열과 slice가 있다.

 

 

 

 

'Go' 카테고리의 다른 글

Struct  (0) 2024.01.04
Maps  (0) 2023.12.30
Pointer  (0) 2023.12.28
If/switch  (0) 2023.12.28
for, range, args  (0) 2023.12.28

+ Recent posts