Go Maps 설명: 키-값 쌍이 실제로 저장되는 방법
게시물 일부 발췌입니다. 전체 게시물은 여기에서 볼 수 있습니다: https://victoriametrics.com/blog/go-map/.
Go를 처음 사용하는 경우 Go에서 지도를 사용하는 방법을 파악하는 것이 다소 혼란스러울 수 있습니다. 경험이 많더라도 지도가 실제로 어떻게 작동하는지 이해하는 것은 꽤 어려울 수 있습니다.
다음 예를 들어보세요. 지도에 '힌트'를 설정했는데 왜 슬라이스처럼 길이와 같은 단순한 것이 아니라 '힌트'라고 불리는지 궁금하신가요?
// hint = 10 m := make(map[string]int, 10)
또는 지도에서 for-range 루프를 사용할 때 순서가 삽입 순서와 일치하지 않으며, 다른 시간에 동일한 지도를 반복하면 변경되기까지 한다는 사실을 눈치채셨을 수도 있습니다. 그런데 이상하게도 정확히 동시에 반복하면 순서는 대개 동일하게 유지됩니다.
이야기가 길어지니 안전벨트 매시고 뛰어들어보세요.
계속 진행하기 전에 미리 알아두세요. 여기에 있는 정보는 Go 1.23을 기반으로 합니다. 상황이 변경되어 최신 정보가 아닌 경우 언제든지 X(@func25)로 핑을 보내주세요.
Map in Go: 빠른 시작
Go의 지도에 대해 이야기해 보겠습니다. 지도는 키-값 저장소 역할을 하는 내장 유형입니다. 0, 1, 2 등과 같이 인덱스가 증가하면서 키를 사용해야 하는 배열과 달리 맵을 사용하면 키는 비교할 수 있는 모든 유형이 될 수 있습니다.
더 많은 유연성을 제공합니다.
m := make(map[string]int) m["a"] = 1 m["b"] = 2 m // map[a:1 b:2]
이 예에서는 make()를 사용하여 키가 문자열이고 값이 정수인 빈 맵을 만들었습니다.
이제 각 키를 수동으로 할당하는 대신 지도 리터럴을 사용하여 시간을 절약할 수 있습니다. 이렇게 하면 맵을 생성할 때 바로 키-값 쌍을 한 번에 설정할 수 있습니다.
m := map[string]int{ "a": 1, "b": 2, }
처음 지도를 만들 때 중괄호 안에 키와 해당 값을 나열하면 됩니다. 그렇게 간단합니다.
나중에 특정 키-값 쌍이 더 이상 필요하지 않다는 것을 알게 되면 Go가 도와드립니다. 원하지 않는 키를 삭제하는 편리한 삭제 기능이 있습니다: delete(m, "a").
맵의 0 값은 nil이며, nil 맵은 어떤 면에서는 빈 맵과 비슷합니다. 그 안에서 키를 찾아볼 수 있으며, Go는 놀라서 프로그램을 중단시키지 않을 것입니다.
존재하지 않는 키를 검색하면 Go는 해당 맵의 값 유형에 대해 조용히 "0 값"을 제공합니다.
var m map[string]int println(m["a"]) // 0 m["a"] = 1 // panic: assignment to entry in nil map
그러나 문제는 nil 맵에 새로운 키-값 쌍을 추가할 수 없다는 것입니다.
사실 Go는 슬라이스를 처리하는 방식과 매우 유사한 방식으로 지도를 처리합니다. 맵과 슬라이스 모두 nil로 시작하며, nil일 때 "무해한" 작업을 수행해도 Go는 당황하지 않습니다. 예를 들어, "드라마" 없이 nil 슬라이스를 반복할 수 있습니다.
그렇다면 0지도를 반복하려고 하면 어떻게 될까요?
var m map[string]int for k, v := range m { println(k, v) }
아무 일도 일어나지 않고, 오류도 없고, 놀랄 일도 없습니다. 그냥 조용히 아무것도 하지 않습니다.
Go의 접근 방식은 모든 유형의 기본값을 프로그램을 폭파시키는 것이 아니라 유용한 것으로 취급하는 것입니다. Go가 문제를 일으키는 유일한 경우는 nil 맵에 새 키-값 쌍을 추가하려고 하거나 슬라이스에서 범위를 벗어난 인덱스에 액세스하는 등 정말 불법적인 일을 할 때입니다.
Go의 지도에 대해 알아야 할 몇 가지 사항이 더 있습니다.
- 지도에 대한 for-range 루프는 특정 순서로 키를 반환하지 않습니다.
- 맵은 스레드로부터 안전하지 않습니다. 동일한 맵을 동시에 읽고(또는 범위를 사용하여 반복) 쓰려고 하면 Go 런타임에서 치명적인 오류가 발생합니다.
- 간단한 ok 확인을 통해 지도에 키가 있는지 확인할 수 있습니다: _, ok := m[key].
- 지도의 키 유형은 비교 가능해야 합니다.
맵 키에 대한 마지막 사항을 자세히 살펴보겠습니다. 앞서 "키는 유사한 유형이 될 수 있다"고 언급했지만, 그 이상의 의미가 있습니다.
"그럼 비교형이란 정확히 무엇이고, 그렇지 않은 것은 무엇인가요?"
매우 간단합니다. ==를 사용하여 동일한 유형의 두 값을 비교할 수 있으면 해당 유형은 비교 가능한 것으로 간주됩니다.
func main() { var s map[int]string if s == s { println("comparable") } } // compile error: invalid operation: s == s (map can only be compared to nil)
하지만 보시다시피 위 코드는 컴파일조차 되지 않습니다. 컴파일러가 다음과 같이 불평합니다. "잘못된 연산: s == s(map은 nil과만 비교할 수 있습니다.)"
이 동일한 규칙은 슬라이스, 함수, 슬라이스나 맵 등을 포함하는 구조체 등 비교 불가능한 다른 유형에도 적용됩니다. 따라서 이러한 유형 중 하나를 맵의 키로 사용하려는 경우 운이 없군요.
func main() { var s map[[]int]string } // compile error: invalid map key type []intcompilerIncomparableMapKey
하지만 여기에 약간의 비밀이 있습니다. 인터페이스는 비교 불가능할 수도 있고 비교 불가능할 수도 있습니다.
무슨 뜻인가요? 컴파일 오류 없이 빈 인터페이스를 키로 사용하여 맵을 절대적으로 정의할 수 있습니다. 하지만 런타임 오류가 발생할 가능성이 높으니 주의하세요.
func main() { m := map[interface{}]int{ 1: 1, "a": 2, } m[[]int{1, 2, 3}] = 3 m[func() {}] = 4 } // panic: runtime error: hash of unhashable type []int // panic: runtime error: hash of unhashable type func()
Everything looks fine until you try to assign an uncomparable type as a map key.
That's when you'll hit a runtime error, which is trickier to deal with than a compile-time error. Because of this, it's usually a good idea to avoid using interface{} as a map key unless you have a solid reason and constraints that prevent misuse.
But that error message: "hash of unhashable type []int" might seem a bit cryptic. What's this about a hash? Well, that's our cue to dig into how Go handles things under the hood.
Map Anatomy
When explaining the internals of something like a map, it's easy to get bogged down in the nitty-gritty details of the Go source code. But we're going to keep it light and simple so even those new to Go can follow along.
What you see as a single map in your Go code is actually an abstraction that hides the complex details of how the data is organized. In reality, a Go map is composed of many smaller units called "buckets."
type hmap struct { ... buckets unsafe.Pointer ... }
Look at Go source code above, a map contains a pointer that points to the bucket array.
This is why when you assign a map to a variable or pass it to a function, both the variable and the function's argument are sharing the same map pointer.
func changeMap(m2 map[string]int) { m2["hello"] = 2 } func main() { m1 := map[string]int{"hello": 1} changeMap(m1) println(m1["hello"]) // 2 }
But don't get it twisted, maps are pointers to the hmap under the hood, but they aren't reference types, nor are they passed by reference like a ref argument in C#, if you change the whole map m2, it won't reflect on the original map m1 in the caller.
func changeMap(m2 map[string]int) { m2 = map[string]int{"hello": 2} } func main() { m1 := map[string]int{"hello": 1} changeMap(m1) println(m1["hello"]) // 1 }
In Go, everything is passed by value. What's really happening is a bit different: when you pass the map m1 to the changeMap function, Go makes a copy of the *hmap structure. So, m1 in the main() and m2 in the changeMap() function are technically different pointers point to the same hmap.
For more on this topic, there's a great post by Dave Cheney titled There is no pass-by-reference in Go.
Each of these buckets can only hold up to 8 key-value pairs, as you can see in the image below.
The map above has 2 buckets, and len(map) is 6.
So, when you add a key-value pair to a map, Go doesn't just drop it in there randomly or sequentially. Instead, it places the pair into one of these buckets based on the key's hash value, which is determined by hash(key, seed).
Let's see the simplest assignment scenario in the image below, when we have an empty map, and assign a key-value pair "hello": 1 to it.
It starts by hashing "hello" to a number, then it takes that number and mods it by the number of buckets.
Since we only have one bucket here, any number mod 1 is 0, so it's going straight into bucket 0 and the same process happens when you add another key-value pair. It'll try to place it in bucket 0, and if the first slot's taken or has a different key, it'll move to the next slot in that bucket.
Take a look at the hash(key, seed), when you use a for-range loop over two maps with the same keys, you might notice that the keys come out in a different order:
func main() { a := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6} b := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6} for i := range a { print(i, " ") } println() for i := range b { print(i, " ") } } // Output: // a b c d e f // c d e f a b
How's that possible? Isn't the key "a" in map a and the key "a" in map b hashed the same way?
But here's the deal, while the hash function used for maps in Go is consistent across all maps with the same key type, the seed used by that hash function is different for each map instance. So, when you create a new map, Go generates a random seed just for that map.
In the example above, both a and b use the same hash function because their keys are string types, but each map has its own unique seed.
"Wait, a bucket has only 8 slots? What happens if the bucket gets full? Does it grow like a slice?"
Well, sort of. When the buckets start getting full, or even almost full, depending on the algorithm's definition of "full", the map will trigger a growth, which might double the number of main buckets.
But here's where it gets a bit more interesting.
当我说“主存储桶”时,我正在设置另一个概念:“溢出存储桶”。当您遇到碰撞频繁的情况时,这些就会发挥作用。想象一下,您有 4 个桶,但其中一个由于高冲突而完全装满了 8 个键值对,而另外 3 个桶则空着。
完整帖子可在此处查看:https://victoriametrics.com/blog/go-map/。
위 내용은 Go Maps 설명: 키-값 쌍이 실제로 저장되는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Golang은 성능과 확장 성 측면에서 Python보다 낫습니다. 1) Golang의 컴파일 유형 특성과 효율적인 동시성 모델은 높은 동시성 시나리오에서 잘 수행합니다. 2) 해석 된 언어로서 파이썬은 천천히 실행되지만 Cython과 같은 도구를 통해 성능을 최적화 할 수 있습니다.

Golang은 동시성에서 C보다 낫고 C는 원시 속도에서 Golang보다 낫습니다. 1) Golang은 Goroutine 및 Channel을 통해 효율적인 동시성을 달성하며, 이는 많은 동시 작업을 처리하는 데 적합합니다. 2) C 컴파일러 최적화 및 표준 라이브러리를 통해 하드웨어에 가까운 고성능을 제공하며 극도의 최적화가 필요한 애플리케이션에 적합합니다.

goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity, 효율성, 및 콘크리 론 피처

Golang은 빠른 개발 및 동시 시나리오에 적합하며 C는 극도의 성능 및 저수준 제어가 필요한 시나리오에 적합합니다. 1) Golang은 쓰레기 수집 및 동시성 메커니즘을 통해 성능을 향상시키고, 고전성 웹 서비스 개발에 적합합니다. 2) C는 수동 메모리 관리 및 컴파일러 최적화를 통해 궁극적 인 성능을 달성하며 임베디드 시스템 개발에 적합합니다.

Golang과 Python은 각각 고유 한 장점이 있습니다. Golang은 고성능 및 동시 프로그래밍에 적합하지만 Python은 데이터 과학 및 웹 개발에 적합합니다. Golang은 동시성 모델과 효율적인 성능으로 유명하며 Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명합니다.

Golang과 C의 성능 차이는 주로 메모리 관리, 컴파일 최적화 및 런타임 효율에 반영됩니다. 1) Golang의 쓰레기 수집 메커니즘은 편리하지만 성능에 영향을 줄 수 있습니다. 2) C의 수동 메모리 관리 및 컴파일러 최적화는 재귀 컴퓨팅에서 더 효율적입니다.

Golang과 C는 각각 공연 경쟁에서 고유 한 장점을 가지고 있습니다. 1) Golang은 높은 동시성과 빠른 발전에 적합하며 2) C는 더 높은 성능과 세밀한 제어를 제공합니다. 선택은 프로젝트 요구 사항 및 팀 기술 스택을 기반으로해야합니다.

golangisidealforbuildingscalablesystemsdueToitsefficiencyandconcurrency
