Maps

Go์˜ map์— ๋Œ€ํ•ด ์•Œ์•„๋ณด์•„์š”

Map

  • Go์—์„œ์˜ map์€ Python๊ณผ JavaScript์˜ object์™€ ๋น„์Šทํ•˜๋‹ค

    • ์™„์ „ํžˆ ๊ฐ™์ง€๋Š” ์•Š๋‹ค!

  • map์„ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด์„œ๋Š” key์™€ value์˜ type์„ ๋ช…์‹œํ•ด์•ผ ํ•œ๋‹ค

    • map[KEY_TYPE]VALUE_TYPE{}

    • ex)

      package main
      
      import "fmt"
      
      func main() {
       chloe := map[string]string{"name": "chloe", "age": "26"}
       fmt.Println(chloe) // -> map[age:26 name:chloe]
      }
      • ์œ„์˜ ์˜ˆ์‹œ์—์„œ value๋กœ string์„ ์‚ฌ์šฉํ•  ๊ฒƒ์ด๋ผ๊ณ  ๋ช…์‹œํ–ˆ์œผ๋ฏ€๋กœ, age์˜ value ๊ฐ’์œผ๋กœ integer 26์„ ๋„ฃ์œผ๋ฉด error๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค

      • value์˜ type ํ•œ ๊ฐ€์ง€๊ฐ€ ์•„๋‹Œ ์—ฌ๋Ÿฌ๊ฐ€์ง€ type์„ ๊ฐ€์ง„ object๋ฅผ ๋งŒ๋“ค๋ ค๋ฉด struct ๊ตฌ์กฐ์ฒด๋ฅผ ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค!

Iterate over a Map using for loop

  • for ์™€ range ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ Map์„ ์ˆœํšŒ ํ•  ์ˆ˜ ์žˆ๋‹ค

    • ex)

      package main
      
      import "fmt"
      
      func main() {
       chloe := map[string]string{"name": "chloe", "age": "26"}
       for key, value := range chloe {
        fmt.Println(key, value)
       }
      }

Last updated