Structs

๋งค๋ ฅ์ ์ธ struct์— ๋Œ€ํ•ด ์•Œ์•„๋ณด์•„์š”

Struct

  • Struct๋Š” object์™€ ๋น„์Šทํ•˜๋ฉด์„œ map ๋ณด๋‹ค ์ข€ ๋” ์œ ์—ฐํ•œ ๊ฒƒ์ด ํŠน์ง•์ด๋‹ค

  • map ์€ ์ง€์ •ํ•œ type์˜ Key์™€ Value๋งŒ ๋„ฃ์„ ์ˆ˜ ์žˆ์ง€๋งŒ, struct๋Š” type์— ์ƒ๊ด€์—†์ด ๊ฐ’์„ ๋„ฃ์„ ์ˆ˜ ์žˆ๋‹ค

  • Struct๋ฅผ ๊ธฐ๋ณธ์ ์œผ๋กœ structure(๊ตฌ์กฐ์ฒด) ์ธ๋ฐ, struct๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค

    1. ์–ด๋–ค struct ์ธ์ง€ ์ •์˜ํ•˜๊ณ 

    2. structure์˜ ํ˜•ํƒœ๋ฅผ ๋งŒ๋“ค์–ด ์ฃผ๋ฉด ๋œ๋‹ค

    3. ex)

      package main
      
      import "fmt"
      
      type person struct {
       name    string
       age     int
       favFood []string
      }
      
      func main() {
       favFood := []string{"guacamole", "omelet", "biscuits and gravy"}
       chloe := person{"chloe", 26, favFood}
       fmt.Println(chloe)
      }

Struct์˜ ๊ฐ’์„ ์ง€์ •ํ•˜๊ธฐ

  1. ์ •์˜ ๋œ ์ˆœ์„œ๋Œ€๋กœ ๊ฐ’์„ ์ง€์ •ํ•˜๊ธฐ

    chloe := person{"chloe", 26, chloeFav}
    • ๋ช…ํ™•ํ•˜๊ฒŒ ์–ด๋–ค value๊ฐ€ ์–ด๋–ค value์ธ์ง€ ๋ณด์ด์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ์ข‹์ง€ ์•Š์€ ๋ฐฉ๋ฒ•์ด๋‹ค

      • ํ•ด๋‹น ๊ฐ’์ด struct์—์„œ ๋ช‡๋ฒˆ์งธ์ธ์ง€ ํ™•์ธํ•ด์•ผ ํ•˜๋Š” ๋ฒˆ๊ฑฐ๋กœ์›€์ด ์žˆ๋‹ค

  2. ์–ด๋–ค ๊ฐ’์ธ์ง€ ๋ช…์‹œํ•˜์—ฌ ์ง€์ •ํ•˜๊ธฐ

    camila := person{name: "camila", age: 26, favFood: camilaFav}
  • struct ๋ฅผ ๋น„๊ตํ•˜๋ฉฐ ํ™•์ธํ•˜์ง€ ์•Š์•„๋„ ๋˜๋ฏ€๋กœ ๋ช…ํ™•ํ•˜๋‹ค

๋‹จ, ๋‘ ๊ฐ€์ง€๋ฅผ ์„ž์–ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜๋Š” ์—†๋‹ค!

Struct ํ™œ์šฉํ•˜๊ธฐ

  • Go๋Š” Java ์ฒ˜๋Ÿผ class ๊ฐ€ ์—†๊ณ , Python์ด๋‚˜ JavsScript์ฒ˜๋Ÿผ object๋„ ์—†๋‹ค

    • Struct๋ฅผ ํ™œ์šฉํ•ด์•ผ ํ•œ๋‹ค!

  • Struct๋กœ method ๋„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค

  • Go๋Š” construct method ๊ฐ€ ์—†๋‹ค

    • Python์˜ __init__, JavaScript์˜ constructor() ๊ฐ™์€ construct๊ฐ€ Go์˜ struct์—๋Š” ์—†๋‹ค

    • ์ง์ ‘ constructor๋ฅผ ๋งŒ๋“ค์–ด ์‹คํ–‰ํ•ด์•ผ ํ•œ๋‹ค

  • Go์—์„œ ๊ฑฐ์˜ ๋ชจ๋“ ๊ฒƒ์„ struct๋ฅผ ํ™œ์šฉํ•˜์—ฌ ํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ struct๋Š” ์ค‘์š”ํ•œ ์—ญํ• ์„ ํ•œ๋‹ค!

Last updated