Go
Go : struct, type, method
mokhs
2022. 3. 20. 15:20
๊ฐ์
- Go์ ๊ตฌ์กฐ์ฒด(struct)์ ํ์ (type) ๊ทธ๋ฆฌ๊ณ ๋ฉ์๋(method)์ ๋ํด์ ์์๋ณด์
๊ตฌ์กฐ์ฒด(struct)
- go์์๋ c์ ๊ตฌ์กฐ์ฒด์ ์ ์ฌํ ํํ๋ฅผ ์ง์ํ๋ค
- ๊ตฌ์กฐ์ฒด๋ฅผ ์ ์ธํจ์ผ๋ก์จ ์๋ก์ด ์๋ฃํ์ ์ ์ธํ ์ ์๊ณ , type-safe์๋ ํจ๊ณผ๊ฐ ์๋ค
- ์๋ ์์๋ฅผ ํตํด ์์๋ณด์
type user struct {
name string
age int
}
func main() {
user := user{name: "mokhs00", age: 23}
fmt.Println(user)
}
receiver์ method
- go์์๋ receiver๋ฅผ ์ด์ฉํด ๋ฉ์๋ ๊ธฐ๋ฅ์ ์ด์ฉํ ์ ์๋ค
func (t T) Foo() {}
ํ์์ด๋ฉฐ ๊ธฐ์กด ํจ์์์ ์์(t *T)
๊ฐ ์ถ๊ฐ๋ ๊ฒ์ด๋ค (T๋ ํ์ ์ด๋ค)- T์ ๋ํ receiver๊ฐ ์กด์ฌํ๋ ํจ์๋ T๋ฅผ ์ด์ฉํด ํด๋น ํจ์๋ฅผ ์ฌ์ฉํ ์ ์๋ค ex)
T.Foo()
- ๊ฒฝ์ฐ์ ๋ฐ๋ผ ์ฐธ์กฐ๊ฐ์ ์ฌ์ฉํด์ผ ํ๋ฏ๋ก ํฌ์ธํฐ๋ฅผ ์ดํดํ๊ณ ์ฌ์ฉํ๋ ๊ฒ์ ์ฃผ์ํ์
- ์ถ๊ฐ๋ก ํจ์๋ ๊ตฌ์กฐ์ฒด์ ๋ํ ์ฃผ์์ ํด๋น ์ฃผ์ฒด์ ๋์ผํ ์ด๋ฆ์ผ๋ก ์์ํด์ผํ๋ค
- ์ฃผ์์ ํตํด ์ฌ์ฉํ๋ ์ฌ๋๋ค์๊ฒ ํํธ๋ฅผ ์ค ์๋ ์๋ค
- ๋ค์ ์์๋ฅผ ํตํด ์์๋ณด์
// Account struct
type Account struct {
owner string
balance int
}
// NewAccount create Account
func NewAccount(owner string) *Account {
account := Account{owner: owner, balance: 0}
return &account
}
// Deposit x amount on the account
func (account *Account) Deposit(amount int) {
account.balance += amount
}
func main() {
a := account.NewAccount("mokhs")
a.Deposit(100)
}
struct String
- ๊ตฌ์กฐ์ฒด๋ฅผ ์ถ๋ ฅํด๋ณด๋ฉด ๋์ค๋ ๋ฌธ์๋ฅผ ๋ณ๊ฒฝํ ์๋ ์๋ค
- ์ถ๋ ฅ ์์ ๊ธฐ๋ณธ์ ์ผ๋ก String ๋ฉ์๋๋ฅผ ์คํํ๊ฒ ๋๋๋ฐ, String ๋ฉ์๋๋ฅผ receiver๋ฅผ ์ด์ฉํด ์ฌ์ ์ํ๋ฉด ์ด๋ฅผ ๋ณ๊ฒฝํ ์ ์๋ค
- ๋ค์ ์์๋ฅผ ํตํด ์์๋ณด์
func (account Account) String() string {
return fmt.Sprint(account.owner, " has: ", account.balance)
}
func main() {
a := account.NewAccount("mokhs")
a.Deposit(100)
// mokhs has:100
fmt.Println(a)
}
ํ์ (type)
- ๊ตฌ์กฐ์ฒด๊ฐ ์๋ ํ์ ์ ์ ์ํ ์ ์๋ค
- ์ด๋ type-safeํ ํ๋ก๊ทธ๋จ์ ์ํด์ ์ ์ฉํ๊ณ , ๋ค์ด๋ฐ์ ํตํด ๊ฐ๋ ์ฑ์ ์ฆ๊ฐ์ํฌ ์ ์๋ค
- ๋ํ ํ์ ๋ ๊ตฌ์กฐ์ฒด์ ๋์ผํ๊ฒ ๋ฉ์๋๋ฅผ ์ถ๊ฐํ ์ ์๋ค
- ์๋ ์์๋ฅผ ํตํด ์์๋ณด์
// dict.go
// Dictionary type
type Dictionary map[string]string
var errNotFoundElement = errors.New("not found element")
func (dictionary Dictionary) Search(word string) (string, error) {
value, exists := dictionary[word]
if exists {
return value, nil
}
return "", errNotFoundElement
}
// main.go
func main() {
dict := dict.Dictionary{}
dict["a"] = "b"
dict.Search("a")
fmt.Println(dict)
}