Golang 同名方法

Golang 同名方法

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

语法

func(reciver_name_1 Type) method_name(parameter_list)(return_type){  
// Code  
}

func(reciver_name_2 Type) method_name(parameter_list)(return_type){  
// Code  
}

让我们借助于例子来讨论这个概念。

例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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程