Recent Comments
Link
Recent Posts
Today
Total
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
관리 메뉴

Study Memory Work

[Go Lang] 구조체 - 선언, 활용 본문

Programing/Go

[Go Lang] 구조체 - 선언, 활용

Hera Choi 2023. 3. 2. 14:37

구조체

  • Go에서 필드들의 집합체, 또는 컨테이너를 구조체라 한다.
  • 구조체는 필드는 갖지만 메소드는 갖지 않는다.
  • 객체지향 방식을 지원한다. -> 리시버를 통해 구조체와 메소드를 연결
  • 상속, 객체, 클래스 개념 없음
// 구조체 선언
type Account struct {
	number   string
	balance  float64 // 잔액
	interest float64 //이자
}

// 리시버를 이요해 메소드와 구조체 연결
func (a Account) Calculate() float64 {
	return a.balance + (a.balance * a.interest)
}

func main() {
	// 인스턴스 생성1
	kim := Account{number: "123-456", balance: 10000000, interest: 0.015}
	// 인스턴스 생성2 (전부 다 값을 채우지 않아도 괜찮다.)
    lee := Account{number: "123-457", balance: 12000000}
	park := Account{number: "123-458", interest: 0.025}
    // 인스턴스 생성3 (순서대로 값만 넣어도 됨)
	cho := Account{"123-459", 15000000, 0.03}

	fmt.Println("ex1 kim : ", kim)
	fmt.Println("ex1 lee : ", lee)
	fmt.Println("ex1 park : ", park)
	fmt.Println("ex1 cho : ", cho)

	fmt.Println("ex2 kim : ", kim.Calculate())
	fmt.Println("ex2 lee : ", lee.Calculate())
	fmt.Println("ex2 park : ", park.Calculate())
	fmt.Println("ex2 cho : ", cho.Calculate())
}

 

구조체 선언 방법

유의해야 할 점은, 인터페이스로 구현된 메소드를 오버라이딩해서 사용하는 경우. 이 메소드가 포인터 형(리시버 메소드)라면 포인터형으로 인스턴스를 생성하고 메소드에 파라미터를 넘길 때에도 &를 사용해주어 넘겨야 한다.

type Account struct {
	number   string
	balance  float64 // 잔액
	interest float64 //이자
}

type car struct {
	color string
	name  string
}

func main() {

	// 1. 포인터형 인스턴스 짧은 선언. 포인터형 객체 만들 때에는 new 필수
	var kim2 *Account = new(Account)
    
	kim2.number = "234-567"
	kim2.balance = 1000000
	kim2.interest = 0.015

	// 2. 포인터형 인스턴스 선언
	hong := &Account{number: "234-568", balance: 15000000, interest: 0.02}
    
    c3 := &car{}
	c4 := &car{"black", "520d"}

	// 3. 일반 인스턴스 짧은 선언
	lee2 := new(Account)
    
	lee2.number = " 2345-709"
	lee2.number = "234-567"
	lee2.balance = 1000000
	lee2.interest = 0.015
    
  	// 4.
    c1 := car{"red", "220d"}
    
    // 5.
	c2 := new(car)
	c2.color, c2.name = "white", "sonata"
    
    
    fmt.Printf("ex3 kim2 : %#v\n", kim2)
	fmt.Printf("ex3 hong : %#v\n", hong)
	fmt.Printf("ex3 lee2 : %#v\n", lee2)

	fmt.Println("ex1 : ", c1)
	fmt.Println("ex1 : ", c2)
	fmt.Println("ex1 : ", c3)
	fmt.Println("ex1 : ", c4)


}

 

구조체 필드 태그 사용법

  • reflect 라이브러리를 이용
  • reflect.TypeOf()
import (
	"fmt"
	"reflect"
)

type Car struct {
	name    string "차량명"
	color   string "색상"
	company string "제조사"
	detail  spec   "상세"
}

func main() {
	tag := reflect.TypeOf(Car{})

	for i := 0; i < tag.NumField(); i++ {
		fmt.Println("ex1 : ", tag.Field(i).Tag, tag.Field(i).Name, tag.Field(i).Type)
	}
}

 

중첩 구조체

type Car struct {
	name    string "차량명"
	color   string "색상"
	company string "제조사"
	detail  spec   "상세"
}

type spec struct {
	lenhth int "전장"
	height int "전고"
	width  int "전축"
}

func main() {
	car1 := Car{"520d", "silver", "bmw", spec{4000, 1000, 2000}}

	fmt.Println("ex1 : ", car1.name)
	fmt.Println("ex1 : ", car1.color)
	fmt.Println("ex1 : ", car1.company)
	fmt.Printf("ex1 : %#v", car1.detail)

	fmt.Println("ex1 : ", car1.detail.height)
	fmt.Println("ex1 : ", car1.detail.width)
	fmt.Println("ex1 : ", car1.detail.lenhth)
}