Golang: Structs Methods and Interface


Go Struct, Methods and Embedding example

package main

import "fmt"

type User struct {
	name, address string
}

type Employee struct {
	level  int
	salary int
	user   User // Embedding
}

/**
 * Greating for User
 */
func (u User) Greeting() string {
	return fmt.Sprintf("Dear %s %s", u.name, u.address)
}

/**
 * Greating for User
 */
func (e Employee) Greeting() string {
	return fmt.Sprintf("Your level %d, Your salary %d", e.level, e.salary)
}

func main() {
	user := User{"Yazid", "Jalan munukan no.19"}

	fmt.Println(user.Greeting())

	employee := Employee{1, 2000, user}

	fmt.Println(employee.user.Greeting())
	fmt.Println(employee.Greeting())
}

Using Pointer to keep the lowest amount of structs per file

package main

import (
	"fmt"
)

type User struct {
	FirstName, LastName string
}

func (u *User) Greeting() string {
	return fmt.Sprintf("Dear %s %s", u.FirstName, u.LastName)
}
func main() {
	u := &User{"Yusuf", "Ibrahim"}
	fmt.Println(u.Greeting())
}

Golang Interface Example

package main

import (
	"fmt"
)

type User struct {
	FirstName, LastName, address string
}

func (u *User) Name() string {
	return fmt.Sprintf("%s %s", u.FirstName, u.LastName)
}

func (u *User) Address() string {
	return fmt.Sprintf("%s", u.address)
}

type Customer struct {
	Id                int
	FullName, address string
}

func (c *Customer) Name() string {
	return c.FullName
}

func (c *Customer) Address() string {
	return fmt.Sprintf("%s", c.address)
}

type Namer interface {
	Name() string
	Address() string
}

func Greet(n Namer) string {
	return fmt.Sprintf("Dear %s at %s", n.Name(), n.Address())
}
func main() {
	u := &User{"Matt", "Aimonetti", "jalan Banda"}
	fmt.Println(Greet(u))

	c := &Customer{42, "Francesc", "jalan Banda"}
	fmt.Println(Greet(c))
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s