go [Type (수조) 에서 []interface {} (can't I assign any slice to an []interface {}) 로 직접 전환할 수 없습니다.
Introduction
Given that you can assign a variable of any type to an interface{}, often people will try code like the following.
var dataSlice []int = foo()
var interfaceSlice []interface{} = dataSlice
This gets the error
cannot use dataSlice (type []int) as type []interface { } in assignment
The question then, "Why can't I assign any slice to an []interface{}, when I can assign any type to an interface{}?"
Why?
There are two main reasons for this.
The first is that a variable with type []interface{} is not an interface! It is a slice whose element type happens to be interface{}. But even given this, one might say that the meaning is clear.
Well, is it? A variable with type []interface{} has a specific memory layout, known at compile time.
Each interface{} takes up two words (one word for the type of what is contained, the other word for either the contained data or a pointer to it). As a consequence, a slice with length N and with type []interface{} is backed by a chunk of data that is N*2 words long.
This is different than the chunk of data backing a slice with type []MyType and the same length. Its chunk of data will be N*sizeof(MyType) words long.
The result is that you cannot quickly assign something of type []MyType to something of type []interface{}; the data behind them just look different.
What can I do instead?
It depends on what you wanted to do in the first place.
If you want a container for an arbitrary array type, and you plan on changing back to the original type before doing any indexing operations, you can just use an interface{}. The code will be generic (if not compile-time type-safe) and fast.
If you really want a []interface{} because you'll be doing indexing before converting back, or you are using a particular interface type and you want to use its methods, you will have to make a copy of the slice.
var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
interfaceSlice[i] = d
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
알림: 현재 지점의 최신 제출이 대응하는 원격 지점보다 뒤떨어지기 때문에 업데이트가 거부됩니다.알림: 다시 밀어넣기 전에 원격 변경과 합칩니다. (예를 들어'git pull...')자세한 내용은 "git push --help"의 "Nogitpush를 사용하다가 오류가 발생했습니다. git fetch origin master 입력: 분기 보기: 로컬 브랜치와 원격 브랜치의 차이점을 살펴보십시오. 결합: 서류 11이 많아졌어요. 로컬 기준으로 덮어쓰...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.