"Go 닐 슬라이스 vs 빈 슬라이스"의 두 판 사이의 차이

 
6번째 줄: 6번째 줄:
* 차이점
* 차이점
** 닐 슬라이스의 값은 nil이고, 빈 슬라이스의 값은 nil이 아니다.
** 닐 슬라이스의 값은 nil이고, 빈 슬라이스의 값은 nil이 아니다.
** Printf("%#v")로 출력하면 각각 <code>[]string(nil)</code>과 <code>[]string{}</code>이 나온다. (문자열 슬라이스인 경우)
** <code>Printf("%#v")</code>로 출력하면 각각 <code>[]string(nil)</code>과 <code>[]string{}</code>이 나온다. (문자열 슬라이스인 경우)
* 공통점
* 공통점
** len() 값은 0이다.
** <code>len()</code> 값은 0이다.
** Println() 또는 Printf("%v")로 출력하면 <code>[]</code>이 나온다.
** <code>Println()</code> 또는 <code>Printf("%v")</code>로 출력하면 <code>[]</code>이 나온다.
** append()로 원소를 추가할 수 있다.
** <code>[[Go append()|append()]]</code>로 원소를 추가할 수 있다.


==예시 1==
==예시 1==

2024년 7월 6일 (토) 19:17 기준 최신판

1 개요[ | ]

Go 슬라이스 제로값
Go 닐 슬라이스 vs 빈 슬라이스
  • 닐 슬라이스와 빈 슬라이스는 같지 않다.
  • 슬라이스제로값닐 슬라이스이다. ★★
  • 차이점
    • 닐 슬라이스의 값은 nil이고, 빈 슬라이스의 값은 nil이 아니다.
    • Printf("%#v")로 출력하면 각각 []string(nil)[]string{}이 나온다. (문자열 슬라이스인 경우)
  • 공통점
    • len() 값은 0이다.
    • Println() 또는 Printf("%v")로 출력하면 []이 나온다.
    • append()로 원소를 추가할 수 있다.

2 예시 1[ | ]

package main

import "fmt"

func main() {
	var a []string
	var b []string = []string{}

	fmt.Println(a == nil)           // true
	fmt.Printf("%#v\n", a)          // []string(nil)
	fmt.Println(len(a))             // 0
	fmt.Println(a)                  // []
	fmt.Printf("%v\n", a)           // []
	fmt.Println(append(a, "hello")) // [hello]

	fmt.Println(b == nil)           // false
	fmt.Printf("%#v\n", b)          // []string{}
	fmt.Println(len(b))             // 0
	fmt.Println(b)                  // []
	fmt.Printf("%v\n", b)           // []
	fmt.Println(append(b, "hello")) // [hello]
}

3 예시 2[ | ]

package main

import (
	"fmt"
	"reflect"
)

func main() {
	var nilSlice []string
	emptySlice := []string{}

	fmt.Println(reflect.DeepEqual(nilSlice, emptySlice)) // false

	fmt.Printf("%#v\n", nilSlice)                   // []string(nil)
	fmt.Println(reflect.ValueOf(nilSlice).IsZero()) // true
	fmt.Println(len(nilSlice))                      // 0

	fmt.Printf("%#v\n", emptySlice)                   // []string{}
	fmt.Println(reflect.ValueOf(emptySlice).IsZero()) // false
	fmt.Println(len(emptySlice))                      // 0
}

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}