Golang不支持函数重载。

Why does Go not support overloading of methods and operators?

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.

Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it.

目前的理解是这样的:
如果2个或多个函数,同名,但接收不同的参数,这是不支持的。
但是,如果多个函数,receiver是不同的,但也同名,这是支持的。


package main

import (
    "fmt"
)

type englishBot struct{}
type spanishBot struct{}

//这下面2个是OK的
func (eb englishBot) greeting() string {
   return "Hello"
}

func (sb spanishBot) greeting() string{
   return "Hola"
}

//下面这2个函数就是重载,不支持,会报错
//所以需要用到interface
func print (eb englishBot) {
   fmt.Println(eb.greeting())
}

func print (sb spanishBot) {
   fmt.Println(sb.greeting())
}

标签: overloading, interface

添加新评论