/ The Blog of Jinho Ko / Computer science / Programming / Golang

·

1 min read

Go에서 OOP를 흉내내는 법

By Jinho Ko

Defining Class

표준 구현체

type Customer struct {                // class definition
	id   int 
	name string
}

func (c *Customer) GetID() int {      // member function
	return c.id
}

a := &Customer{}  // new Customer(v1,v2,v3...)value initialization
a.id = 1         // member access

어떤 struct type이 interface를 implement한다는 개념은 없음. Interface는 implicit함. 즉 type X interface ( GetID() int )라는 interface가 있다면, 그 Customer는 X의 interface를 자동으로 implement한 것이 됨.

Constructor

  • constructor 개념은 없음.
  • 아니면 아래 방법과 같이 factory pattern을 이용해
    • New(input) *ClassName {} 식으로 써도 가능.
func New(name string, width float64, height float64) *Rectangle {
    instance := &Rectangle{Name: name, Width: width, Height: height}
		// constructor method part

		return instance
}

Getter / Setter function

외부에서 변수를 바로 접근하기 싫다면, 멤버변수를 소문자로 하고, 대문자로 되어있는 getter/setter함수를 정의.

func (part *Part)GetName string {
    return part.name
}

func (part *Part) SetName(name string) {
    part.name = name
}

Inheritance

type Vehicle struct {
	Seats int                   // 소문자로 정의하면 child class에서 readonly로만 접근 가능
	Color string                   // 밖에서는 접근불가능. 
}

type Car struct {
	Vehicle
  MyVariable int
}

func main() {
	car := &Car{
		Vehicle{
			Seats: 4,
			Color: "blue",
		},
	}

fmt.Println(car.Seats)
fmt.Println(car.Vehicle.Seats)

Polymorphism

Go에서는 상속이 기본적으로 composition으로 작동함.

다중상속때문에 fmt.Println(car.Vehicle.Seats) 이런 expression이 필요함.

interface 어떻게? 해결? TODO

Files

한 file(모듈)에는 한 class만 넣도록. 다른 class를 module import 해서 부르기.

Good References to Follow Up

comments powered by Disqus

© Copyright 2024. Jinho Ko. All rights reserved.