Go 사용자 정의 타입 - struct
목차
Go의 객체 지향
Go는 클래스와 상속 개념이 없다. 대신 구조체(struct) 로 객체 지향 타입을 정의하고, 구조체와 메서드를 연결하여 클래스처럼 사용한다.
- 상태와 메소드를 분리해서 정의 (결합성 없음)
- 사용자 정의 타입: 구조체, 인터페이스, 기본타입, 함수
예제
import "fmt"
// 사용자 정의 타입(구조체)
type Car struct {
name string
color string
price int64
tax int64
}
//구조체 <-> 메소드 바인딩
func (c Car) Price() int64 {
return c.price + c.tax
}
func main() {
bmw := Car{name: "520d", price: 54500000, color: "white", tax: 545000}
benz := Car{name: "220d", price: 74500000, color: "white", tax: 745000}
bmwPrice := bmw.Price()
benzPrice := benz.Price()
fmt.Println("ex1 : ", &bmw)
fmt.Println("ex1 : ", bmwPrice)
fmt.Println("ex1 : ", bmw.Price())
fmt.Println("ex1 : ", &benz)
fmt.Println("ex1 : ", benzPrice)
fmt.Println("ex1 : ", benz.Price())
}타입 자동 변환 안됨
import "fmt"
type cnt int
func main() {
//예제1
a := cnt(5)
fmt.Println("ex1 : ", a)
//예제2
var b cnt = 15
fmt.Println("ex2 : ", b)
//testConvertT(b) //예외 발생 (중요!) 사용자 정의 타입 <-> 기본 타입 : 매개변수 전달 시에 변환해야 사용 가능 (cnt(5), int(5))
testConvertT(int(b))
testConvertD(b)
testConvertD(cnt(10)) //사용 가능
//testConvertD(int(b)) //예외 발생 (중요!) 사용자 정의 타입 <-> 기본 타입 : 매개변수 전달 시에 변환해야 사용 가능 (cnt(5), int(5))
}
func testConvertT(i int) {
fmt.Println("ex 2 : (Default Type) : ", i)
}
func testConvertD(i cnt) {
fmt.Println("ex 2 : (Custom Type) : ", i)
}