📜  Golang 中的同名方法

📅  最后修改于: 2021-10-24 14:13:29             🧑  作者: Mango

在 Go 语言中,允许在同一个包中创建两个或多个同名的方法,但这些方法的接收者必须是不同的类型。这个特性在 Go函数中不可用,这意味着你不能在同一个包中创建同名方法,如果你尝试这样做,那么编译器会抛出错误。

句法:

让我们在示例的帮助下讨论这个概念:

示例 1:

// Go program to illustrate how to
// create methods of the same name
package main
  
import "fmt"
  
// Creating structures
type student struct {
    name   string
    branch string
}
  
type teacher struct {
    language string
    marks    int
}
  
// Same name methods, but with
// different type of receivers
func (s student) show() {
  
    fmt.Println("Name of the Student:", s.name)
    fmt.Println("Branch: ", s.branch)
}
  
func (t teacher) show() {
  
    fmt.Println("Language:", t.language)
    fmt.Println("Student Marks: ", t.marks)
}
  
// Main function
func main() {
  
    // Initializing values
    // of the structures
    val1 := student{"Rohit", "EEE"}
  
    val2 := teacher{"Java", 50}
  
    // Calling the methods
    val1.show()
    val2.show()
}

输出:

Name of the Student: Rohit
Branch:  EEE
Language: Java
Student Marks:  50

说明:在上面的例子中,我们有两个同名的方法,即show(),但是接收器的类型不同。这里第一个show()方法包含 s 个学生类型的接收器,第二个show()方法包含 t 个教师类型的接收器。在main()函数,我们借助各自的结构变量调用这两个方法。如果您尝试使用相同类型的接收器创建此show()方法,则编译器会抛出错误。

示例 2:

// Go program to illustrate how to
// create the same name methods
// with non-struct type receivers
package main
  
import "fmt"
  
type value_1 string
type value_2 int
  
// Creating same name function with
// different types of non-struct receivers
func (a value_1) display() value_1 {
  
    return a + "forGeeks"
}
  
func (p value_2) display() value_2 {
  
    return p + 298
}
  
// Main function
func main() {
  
    // Initializing the values
    res1 := value_1("Geeks")
    res2 := value_2(234)
  
    // Display the results
    fmt.Println("Result 1: ", res1.display())
    fmt.Println("Result 2: ", res2.display())
}

输出:

Result 1:  GeeksforGeeks
Result 2: 532