Arrays and Slices

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

Arrays

  • Go์—์„œ๋Š” array๋ฅผ ๋งŒ๋“ค๋•Œ์—๋Š” ํ•ด๋‹น array์˜ length๋ฅผ ๋ช…์‹œํ•ด ์ฃผ์–ด์•ผ ํ•œ๋‹ค

    • ex)

      package main
      
      import "fmt"
      
      func main() {
       names := [5]string{"chloe", "camila", "bella"}
       names[3] = "charlotte"
       names[4] = "bree"
       fmt.Print(names)
      }
      • Go์˜ index๋Š” 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋ฏ€๋กœ ์œ„์˜ ์˜ˆ์‹œ์—์„œ names[4]๋Š” 5๋ฒˆ์งธ index์ด๋‹ค

    • array๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ๋ช…์‹œํ•œ ๊ธธ์ด๋ณด๋‹ค ํฐ index๋ฅผ ๋„ฃ์œผ๋ฉด errorr๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค

Slices

  • Array์˜ ํฌ๊ธฐ๋ฅผ ์ œํ•œํ•˜๊ณ  ์‹ถ์„ ๋•Œ๋„ ์žˆ์ง€๋งŒ, array์˜ ํฌ๊ธฐ์— ์ œํ•œ ์—†์ด element๋ฅผ ์ถ”๊ฐ€ ํ•˜๊ณ  ์‹ถ์„ ๋•Œ๋„ ์žˆ์„ ๊ฒƒ์ด๋‹ค

    • ๊ทธ๋Ÿด ๋•Œ ์“ธ ์ˆ˜ ์žˆ๋Š” data type์ด slice ์ด๋‹ค

  • Go์—์„œ์˜ slice๋Š” array์ธ๋ฐ length๊ฐ€ ์—†๋Š” ๊ฒƒ์ด๋‹ค

    • ex)

      package main
      
      import "fmt"
      
      func main() {
       states := []string{"Florida", "Kentucky"}
       fmt.Println(states)
      }
      • array์™€์˜ ์ฐจ์ด์ ์€ length๊ฐ€ ์—†๋‹ค๋Š” ๊ฒƒ ๋ฟ์ด๋‹ค

append()

  • Slice์— item์„ ์ถ”๊ฐ€ํ•  ๋•Œ์—๋Š” append() function์„ ์‚ฌ์šฉํ•œ๋‹ค

  • append()๋Š” ๋‘ ๊ฐœ์˜ argument๋ฅผ ๊ฐ–๋Š”๋‹ค

    1. slice

    2. value

  • ํ•˜์ง€๋งŒ append()๋Š” slice ๋ฅผ ์ˆ˜์ •ํ•˜์ง€๋Š” ์•Š๋Š”๋‹ค

    • append() ์ƒˆ๋กœ์šด ๊ฐ’์ด ์ถ”๊ฐ€๋œ slice๋ฅผ return ํ•œ๋‹ค!

      • ๊ทธ๋Ÿฌ๋ฏ€๋กœ ํ•ด๋‹น slice์— ๋‹ค์‹œ update ํ•ด์ค˜์•ผ ํ•œ๋‹ค

      • ex)

        package main
        
        import "fmt"
        
        func main() {
         states := []string{"Florida", "Kentucky"}
         states = append(states, "California")
         fmt.Println(states)
        }

์•„๋งˆ ๋Œ€๋ถ€๋ถ„ slice๋ฅผ ์‚ฌ์šฉํ•˜๊ฒŒ ๋  ๊ฒƒ ๊ฐ™๋‹ค!

Last updated