Skip to main content

Go Example

package main

type ak47 struct {
gun
}

func newAk47() iGun {
return &ak47{
gun: gun{
name: "AK47 gun",
power: 4,
},
}
}
package main

type gun struct {
name string
power int
}

func (g *gun) setName(name string) {
g.name = name
}

func (g *gun) getName() string {
return g.name
}

func (g *gun) setPower(power int) {
g.power = power
}

func (g *gun) getPower() int {
return g.power
}
package main

type iGun interface {
setName(name string)
setPower(power int)
getName() string
getPower() int
}
package main

type musket struct {
gun
}

func newMusket() iGun {
return &musket{
gun: gun{
name: "Musket gun",
power: 1,
},
}
}
package main

import "fmt"

func getGun(gunType string) (iGun, error) {
if gunType == "ak47" {
return newAk47(), nil
}
if gunType == "musket" {
return newMusket(), nil
}
return nil, fmt.Errorf("Wrong gun type passed")
}
package main

import "fmt"

func main() {
ak47, _ := getGun("ak47")
musket, _ := getGun("musket")

printDetails(ak47)
printDetails(musket)
}

func printDetails(g iGun) {
fmt.Printf("Gun: %s", g.getName())
fmt.Println()
fmt.Printf("Power: %d", g.getPower())
fmt.Println()
}