GoLang ile Struct Method ve Inheritance Kullanımı
Bir süre önce Hello World! ile başladığım GoLang macerama Struct yapılar, Struct Method ve içiçe struct yapılarının inheritance (kalıtım) olarak kullanımı ile devam ediyorum.
Aşağıdaki örnek kod parçacığımızda bu yapıları birarada görebiliriz.
import "fmt"
type Person struct {
firstName string
lastName string
fatherName string
motherName string
citizenShipID int64
}
type Student struct {
identity Person
class int
}
func (c Student) save() {
fmt.Println("Eklendi")
fmt.Println(c.identity.fatherName)
}
func Demo2() {
st := Student{class: 1, identity: Person{firstName: "Burak", lastName: "Şekercioğlu", fatherName: "XYZ", motherName: "YXZ", citizenShipID: 12345678901}}
st.save()
}
Sizin de görebileceğiniz üzere Person olarak kimlik verilerinden
type Person struct {
firstName string
lastName string
fatherName string
motherName string
citizenShipID int64
}
oluşturulan bir struct yapı aynı zamanda Student struct yapısının da kimlik “identity” bilgisini içermektedir.
type Student struct {
identity Person
class int
}
peki biz bu yapıyı oluşturduktan sonra Student yapısında kayıt yapmak istersek nasıl olacak?
O zaman da bir metod tanımlayıp bu metodun Student altında olduğunu bildirmemiz gerekir. Bu sayede Student yapısından türetilen değişkenlerimizde doğrudan kullanabiliriz.
func (c Student) save() {
fmt.Println("Eklendi")
fmt.Println(c.identity.fatherName)
}
aşağıdaki gibi Student yapısından st değişkeni ile içiçe verileri oluşturup doğrudan save metodumuzu çağırabiliriyoruz.
func Demo2() {
st := Student{class: 1, identity: Person{firstName: "Burak", lastName: "Şekercioğlu", fatherName: "XYZ", motherName: "YXZ", citizenShipID: 12345678901}}
st.save()
}
Örnek ekran çıktımız aşağıdaki gibi olacaktır.
D:\Projeler\Go>go run main.go
Eklendi
XYZ