Translate

martes, 1 de noviembre de 2022

Interface y polimorfismo en Go

 


En Go no existen las clases pero si existe la programación orientada a objetos, veamos un ejemplo


package main


import (

 "fmt"

 "bufio"

 "os"

 "strings"

)


type Animal interface {

Eat()

Move()

Speak()

GetName() string

}


type Cow struct { name string }


func (c Cow) Eat() {

fmt.Println("grass")

}


func (c Cow) Move() {

fmt.Println("walk")

}


func (c Cow) Speak() {

fmt.Println("moo")

}


func (c Cow) GetName() string {

return c.name

}



type Bird struct { name string }


func (c Bird) Eat() {

fmt.Println("worms")

}


func (c Bird) Move() {

fmt.Println("fly")

}


func (c Bird) Speak() {

fmt.Println("peep")

}


func (c Bird) GetName() string {

return c.name

}


type Snake struct { name string }


func (c Snake) Eat() {

fmt.Println("mice")

}


func (c Snake) Move() {

fmt.Println("slither")

}


func (c Snake) Speak() {

fmt.Println("hsss")

}


func (c Snake) GetName() string {

return c.name

}


func main() {


animals := make([]Animal, 0, 0)

var animal *Animal

for {

    fmt.Print("< ")

inputStr := get_input()

input := strings.Split(inputStr, " ")

if (len(input) == 1 && input[0] == "quit") {

break

if len(input) == 3 && input[0] == "newanimal" {

aniStr := input[2]

switch aniStr {

case "cow":

animals = append(animals,Cow{ input[1] })

fmt.Println(" Created it! ")

case "bird":

       animals = append(animals,Bird{ input[1] })

fmt.Println(" Created it! ")

case "snake":

animals = append(animals,Snake{ input[1] })

fmt.Println(" Created it! ")

default:

fmt.Println("incorrect input animal")

}

}

if len(input) == 3 && input[0] == "query" {

    animal = find(animals, input[1])

if animal == nil {

fmt.Println("incorrect animal name")

} else {

actionStr := input[2]

switch actionStr {

case "eat":

(*animal).Eat()

case "move":

(*animal).Move()

case "speak":

(*animal).Speak()

default:

fmt.Println("incorrect input action")

break

}

}

}

}


func find(animals []Animal, name string) *Animal {

for i := 0; i < len(animals); i++ {

if animals[i].GetName() == name {

return &animals[i]

}

}

return nil

}


func get_input() string {

    

  var input_string string

    var input []byte

    var err error

    

    for {

        

        reader := bufio.NewReader(os.Stdin)


        input, _ , err = reader.ReadLine()

        

        if err != nil{

            fmt.Println("Something going wrong! Try again")

        } else { 

    input_string = string(input)

            break

        } 

    }

    return input_string

}