Moige
Moige

Reputation: 46

Understanding interfaces in Golang

I'm trying to understand interfaces in Go. I wrote this:

package main

import "fmt"

type Animal struct {
    Name    string
    Ability string
}

type AbilityShower interface {
    ShowAbility() string
}

func (a Animal) ShowAbility() string {
    return fmt.Sprintf("%s can %s", a.Name, a.Ability)
}

func main() {
    var Dog Animal = Animal{
        Name:    "Dog",
        Ability: "Walk",
    }

    Dog.ShowAbility()
}

But when I run with go run main.go nothing appears in the console. What am I doing incorrectly?

Upvotes: 0

Views: 204

Answers (3)

Himanshu
Himanshu

Reputation: 12685

Here you are using fmt.Sprintf which actually works like Scanf returning value. You need to assign that value to a variable and print the output.

func main() {
    var Dog Animal = Animal{
        Name:    "Dog",
        Ability: "Walk",
    }

    output := Dog.ShowAbility()
    fmt.Println(output)
}

If you wants to print when calling the function ShowAbility() you can use Printf function of fmt package.

func (a Animal) ShowAbility() {
    fmt.Printf("%s can %s", a.Name, a.Ability)
}

func main() {
    var Dog Animal = Animal{
        Name:    "Dog",
        Ability: "Walk",
    }

    Dog.ShowAbility()
}

Upvotes: 0

kristianp
kristianp

Reputation: 5905

You are returning a string from the ShowAbility method, but not outputting it.

package main

import "fmt"

type Animal struct {
    Name    string
    Ability string
}

type AbilityShower interface {
    ShowAbility() 
}

func (a Animal) ShowAbility() {
    fmt.Printf("%s can %s", a.Name, a.Ability)
}

func main() {
   var Dog Animal = Animal{
       Name:    "Dog",
       Ability: "Walk",
   }

   Dog.ShowAbility()
}

Upvotes: 0

Anuruddha
Anuruddha

Reputation: 3245

You are not printing the result. Change the main to

func main() {
    var Dog Animal = Animal{
        Name:    "Dog",
        Ability: "Walk",
    }

    fmt.Println(Dog.ShowAbility())
}

FYI: fmt.Sprintf() returns a string and doesn't print it to standard output

// Sprintf formats according to a format specifier and returns the resulting string.

Upvotes: 2

Related Questions