function - 了解 Golang 中的接口(interface)

标签 function go interface stdout

我正在尝试理解 Go 中的接口(interface)。我写了这个:

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()
}

但是当我使用 go run main.go 运行时,控制台中什么也没有出现。我做错了什么?

最佳答案

您没有打印结果。将主要更改为

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

    fmt.Println(Dog.ShowAbility())
}

仅供引用:fmt.Sprintf() 返回一个字符串并且不会将其打印到标准输出

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

关于function - 了解 Golang 中的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48859574/

相关文章:

go - 带 viper 的动态组名

java - 将包含 boolean 值的文本文件作为对象读取到数组列表中

c# - 合并两个实现相同接口(interface)的类列表

c++ - 递归C++函数计算: Bn(a) = Bn−1(a) × Bn−2(a) where B1(a) = B2(a) = a

arrays - 如何将数组发送到函数

linux - 所有 Linux 发行版中的/proc/[pid]/stat 是否始终可用?

go - 如何在控制台的新行上打印 slice 内容?

node.js - 函数参数 - id 与对象

javascript - 我不想运行函数,只是将其用作参数,但它不断弹出

c# - 在 C# 中,一个类可以继承另一个类和接口(interface)吗?