Study Memory Work
[Go Lang] 사용자 정의 타입 본문
- Go는 객체 지향 타입을 구조체로 정의한다. (클래스, 상속 개념이 없음)
- Go는 전형적인 객체지향의 특징을 가지고 있지는 않지만 인터페이스 등을 통한 다형성 지원, 구조체를 통한 클래스형태의 코딩이 가능하도록 이루어져 있다. ( Go는 객체지향 프로그래밍 이다.)
- 객체지향 활용 첫번째 : 구조체
- 클래스 없이 상태, 메소드를 분리해서 정의한다 (결합성 없음)
- 구조체와 메소드를 연결하여 타 언어의 클래스 형식처럼 사용 가능하다(객체지향)
- 사용자 정의 타입 : 구조체, 인터페이스, 기본 타입(int, float, string ...), 함수
사용자 정의 구조체
- 구조체
// 사용자 정의 구조체
type Car struct {
name string
color string
price int
tax int
}
- 일반 메소드
func Price(c Car) int {
return c.price + c.tax
}
- 구조체와 메소드 연결 (객체지향).
- 구조체 내에 해당 메소드가 존재하는 것처럼 사용 가능
func (c Car) Price() int {
return c.price + c.tax
}
- 구조체, 메소드 사용 예제
- main()
func main() {
// 객체 생성
bmw := Car{name: "520b", price: 50000000, color: "write", tax: 5000000}
benz := Car{name: "2200b", price: 70000000, color: "black", tax: 7000000}
fmt.Println("ex 1 : ", Price(bmw)) // 일반적은 메소드 호출
fmt.Println("ex 1 : ", Price(benz))
fmt.Println("ex 2 : ", bmw.Price()) // 마치 클래스 처럼 객체에서 Price 메소드 호출 가능
fmt.Println("ex 2 : ", benz.Price())
}
사용자 정의 기본 자료형 타입
type cnt int
func testConverT(i int) {
fmt.Println("ex 3 : (Default Type)", i)
}
func testConverD(i cnt) {
fmt.Println("ex 4 : (Customtype Type)", i)
}
func main() {
// 초기화
a := cnt(5) // 메소드로 혼동을 줄 수 있기 때문에
fmt.Println("ex 1 : ", a)
var b cnt = 15 // 주로 이 방식으로 값을 할당한다.
fmt.Println("ex 2 : ", b)
//testConverT(a) cnt는 또하나의 Type이기 때문에 int로 인식되지 않는다
testConverD(b)
}
사용자 정의 함수
- 함수를 type으로 선언 :
type totCost func(int, int) int
- 선언한 totCost 함수 사용
func describe(cnt int, price int, fn totCost) {
// 실제로 이렇게 함수를 매개변수로 받는 형식을 많이 취한다.
fmt.Printf("cnt : %d, price : %d, orderPrice: %d", cnt, price, fn(cnt, price))
}
func main() {
// 사용하기
var orderPrice totCost
// totCost 형식에 맞춰 함수를 작성해주어야 함
orderPrice = func(cnt int, price int) int {
return (cnt * price) + 100000
}
describe(5, 20000, orderPrice)
}
사용자 정의 함수 (포인터형)
- reciever == 구조체 메소드.
- 일반 메소드는 기본이 값 전달 방식이고 slice, map등의 객체의 경우에는 참조 전달 방식
- 리시버도 포인터를 활요하여 참조전달 방식으로 메소드를 구현할 수 있다.
- 값 : 일반 함수와 마찬자기로 값 복사 후 함수호출 시 파라미터로 전달 (Default)
- 참조 : 포인터 형식으로 메소드를 정의하면 알아서 포인터형으로 파라미터가 전달됨
- 포인터형 함수 예제
func (b *shoppingBasket) rePurchaseP(cnt, price int) {
b.cnt += cnt
b.price += price
}
- 포인터형 함수, 일반 함수 비교 예제
package main
import "fmt"
type shoppingBasket struct {
cnt int
price int
}
func (b shoppingBasket) purchase() int {
return b.cnt * b.price
}
// 원본을 수정하는 포인터 형식
func (b *shoppingBasket) rePurchaseP(cnt, price int) {
b.cnt += cnt
b.price += price
}
// 원본수정 없이 값 전달만
func (b shoppingBasket) rePurchaseD(cnt, price int) {
b.cnt += cnt
b.price += price
}
func main() {
bs1 := shoppingBasket{cnt: 3, price: 5000}
fmt.Println("ex1 : ", bs1.purchase())
fmt.Println(" -------------- ")
bs1.rePurchaseP(2, 10000)
fmt.Println("ex2 : ", bs1.cnt, bs1.price)
fmt.Println("ex2 : ", bs1.purchase())
fmt.Println(" -------------- ")
bs1.rePurchaseD(2, 10000)
fmt.Println("ex3 : ", bs1.cnt, bs1.price)
fmt.Println("ex3 : ", bs1.purchase())
}
출력 :
ex1 : 15000 -------------- ex2 : 5 15000 ex2 : 75000 -------------- ex3 : 5 15000 ex3 : 75000 |
'Programing > Go' 카테고리의 다른 글
[Go Lang] 구조체 - 생성자 패턴 (0) | 2023.03.02 |
---|---|
[Go Lang] 구조체 - 선언, 활용 (0) | 2023.03.02 |
[Go Lang] File IO : 파일 읽기 (0) | 2023.02.28 |
[Go Lang] File IO : 파일 쓰기 (0) | 2023.02.27 |
[Go Lang] 에러처리 (0) | 2023.02.27 |