Go interfaces

Go interfaces

June 22, 2020
go, programming, cs

tags
Go Programming Programming Code snippets

The following implements a DataModel, like Django’s Model class which requires Validate and Save methods be implemented by whoever uses that Interface. The problem is the Model. m object will be nil, because Model cannot access the User due to the embedded Model struct within the User struct.

package main

import "fmt"

type DataModel interface {
	Validate()
	Save()
}

type Model struct {
	DataModel
}

func (m *Model) Validate(){
	fmt.Println("Validating..", m)
}

func (m *Model) Save(){
	fmt.Println("Saving..", m)
}

type User struct {
	name string
	Model
}

func main(){
	user := &User{name: "Benjamin"}
	fmt.Println(user)
	user.Validate()
	user.Save()
}
&{Benjamin {<nil>}}
Validating.. &{<nil>}
Saving.. &{<nil>}