doremifasodo0008008 2017-03-10 20:15
浏览 82
已采纳

Go中的泛型函数

I'm in the process of learning Go and the documentation and interactive lessons say that an empty interface can hold any type, as it requires no additionally implemented methods.

So for an example:

func describe(i interace{}) {
    fmt.Printf("Type: %T | Value: %v
", i, i)
}

...would print out...

"Type: int | Value: 5" // for i := 5
"Type: string | Value: test" // for i := "test"
... etc

So I guess my question is if this is Go's way of implementing generic functions or if there is another, more suitable, way of doing them.

  • 写回答

2条回答 默认 最新

  • dtyw10299 2017-03-10 23:20
    关注

    The Go paradigm is generally to avoid this by implementing the behavior in non-empty interfaces. For example, say you wanted to print something with type-specific formatting:

    func Print(i interface{}) {
        switch o := i.(type) {
            case int64:
                fmt.Printf("%5d
    ", o)
            case float64:
                fmt.Printf("%7.3f
    ", o)
            case string:
                fmt.Printf("%s
    ", o)
            default: // covers structs and such
                fmt.Printf("%+v
    ", o)
        }
    }
    

    Alternatively, you could define an interface for things that know how to string themselves (this exists in the base library as an fmt.Stringer), and use that:

    type Stringer interface {
        String() string
    }
    
    func Print(o Stringer) {
        fmt.Println(o.String())
    }
    
    type Foo struct {
        a, b int
    }
    
    func (f Foo) String() string {
        // Let's use a custom output format that differs from %+v
        return fmt.Sprintf("%d(%d)", f.a, f.b) 
    }
    
    type Bar struct {
        t bool
    }
    
    func (b Bar) String() string {
        if b.t {
            return "TRUE! =D"
        }
        return "false =("
    }
    

    https://play.golang.org/p/Ez6Hez6cAv

    This lets you have a generic-like functionality, but still retain type safety and have the behavior itself defined by the types, rather than your generic function.

    Go encourages you to think of types in this way, based on their behavior, what they can do rather than what they contain.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答