2012-07-31 6 views
41

Go 언어를 처음 사용합니다. 나는 자신이 arrayslice 데이터 타입과 혼동하는 것을 발견했다.lang 배열 및 슬라이스 데이터 유형 이동

There are major differences between the ways arrays work in Go and C. In Go,

  • Arrays are values. Assigning one array to another copies all the elements.
  • In particular, if you pass an array to a function, it will receive a copy of the array, not a pointer to it.
  • The size of an array is part of its type. The types [10]int and [20]int are distinct.

기능 : 나는 그것을 선언 할 때

As in all languages in the C family, everything in Go is passed by value. That is, a function always gets a copy of the thing being passed, as if there were an assignment statement assigning the value to the parameter. For instance, passing an int value to a function makes a copy of the int, and passing a pointer value makes a copy of the pointer, but not the data it points to.

sort.Ints(arrayValue)가 전달 된 변수를 수정 않습니다를 배열로가 아닌 슬라이스로 다음과 같이

이동 문서에서

, 배열은 설명?

코드

var av = []int{1,5,2,3,7} 

fmt.Println(av) 
sort.Ints(av) 
fmt.Println(av) 
return 

출력

[1 5 2 3 7] 
[1 2 3 5 7] 

답변

31

페이지의 "Slices: usage and internals"

var av = []int{1,5,2,3,7} 

. 정렬 기능은 슬라이스가 참조하는 것의 내용을 수정합니다 이유를 설명

A slice literal is declared just like an array literal, except you leave out the element count.

.

아래와 같이 Kirk으로 주석 처리 된 것처럼, sort.Ints은 조각 대신 배열을 전달하면 오류가 발생합니다.

func Ints(a []int) 
+1

또한 sort.Ints를 사용하면 슬라이스가 아닌 배열. sort.Ints 문서는 슬라이스를 지정합니다. https://golang.org/pkg/sort/#Ints – Kirk

+0

@Kirk 좋은 지적. 나는 그것을 더 많은 가시성을 위해 대답에 포함 시켰습니다. – VonC

34

당신이 조각이 아닌 배열을 사용하기 때문에.

var av = []int{1,5,2,3,7} 

그리고 그이 배열은 다음과 같습니다 :

var av = [...]int{1,5,2,3,7} 
fmt.Println(av) 
sort.Ints(av) 
fmt.Println(av) 

, 당신은 오류가 발생합니다 : 컴파일하려고하면

var av = [...]int{1,5,2,3,7} 
var bv = [5]int{1,5,2,3,7} 

조각이

cannot use av (type [5]int) as type []int in function argument

으로 sort.Ints는 slice []int을받을 것으로 예상됩니다. 슬라이스가 아닌 배열

+1

그래서 슬라이스는 배열 "참조"와 비슷합니까? – allyourcode

+7

예, 슬라이스는 배열 요소에 대한 포인터와 길이로 구성됩니다. 따라서 배열의 하위 섹션 (배열의 '슬라이스')에 대한 참조입니다. – mfhholmes

+0

@mfhholmes 감사합니다. 이것은 IMHO에서 가장 간결한 설명입니다. –

10

[]int{1,5,2,3,7}은 배열이 아닙니다. 배열의 길이는 [5]int{1,5,2,3,7}과 같습니다.

하면 조각의 복사본을 만들고 대신 정렬 :

배열을 만들려면 구문이되어야합니다

a := []int{1,5,2,3,7} 
sortedA := make([]int, len(a)) 
copy(sortedA, a) 
sort.Ints(sortedA) 
fmt.Println(a) 
fmt.Println(sortedA) 
+3

길이가 아니라 ...가있을 수도 있습니다. [...] int {1,2,3} –

+0

@ArtemShitov 맞아, 구문론적인 도움이되는 설탕이야. 컴파일러는 그것을 [3] int {1,2,3}'로 변환 할 것입니다. –

2
var av = []int{1,5,2,3,7} 

당신이 배열처럼 슬라이스를 초기화하는 위의 성명에서

var av = [5]int{1,5,2,3,7}