English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang 基础教程

Golang 控制语句

Golang 函数 & 方法

Golang 结构体

Golang 切片 & 数组

Golang 字符串(String)

Golang 指针

Golang 接口

Golang 并发

Golang 异常(Error)

Golang 其他杂项

Metodo Omoneo di Go

在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:

package main 
  
import "fmt"
  
//创建结构体
type student struct { 
    name  string 
    branch string 
} 
  
type teacher struct { 
    language string 
    marks  int
} 
  
//名称相同的方法,但有不同类型的接收器
func (s student) show() { 
  
    fmt.Println("Nome dello Studente:", s.name) 
    fmt.Println("Corso: ", s.branch) 
} 
  
func (t teacher) show() { 
  
    fmt.Println("Lingua:", t.language) 
    fmt.Println("Studente Voti: ", t.marks) 
} 
  
func main() { 
  
    // Inizializzazione valori delle strutture
    val1 := student{"Rohit", "EEE"} 
  
    val2 := teacher{"Java", 50} 
  
    // Chiamata metodo
    val1.show() 
    val2.show() 
}

Output:

Nome dello Studente: Rohit
Corso: EEE
Lingua: Java
Studente Voti: 50

Istruzioni per l'uso:Nell'esempio sopra, abbiamo due metodi con lo stesso nomeshow()Ma i tipi dei ricevitori sono diversi. Qui, il primoshow()Il metodo contiene un ricevitore di tipo s student, il secondoshow()Il metodo contiene un ricevitore di tipo t teacher. Inmain()All'interno della funzione, utilizziamo le variabili delle strutture rispettive per chiamare questi metodi. Se si tenta di creare questo metodo utilizzando ricevitori di tipo ugualeshow()Se si tenta di creare questo metodo con ricevitori di tipo uguale, il compilatore genererà un errore.

Esempio 2:

// Creazione di metodi con lo stesso nome
// Ricevitori di tipo non strutturato
package main 
  
import "fmt"
  
type value_1 string 
type value_2 int
  
// Creazione di funzioni con lo stesso nome
// Ricevitori non strutturati di tipo diverso
func (a value_1) display() value_1 { 
  
    return a + ".com"
} 
  
func (p value_2) display() value_2 { 
  
    return p + 298 
} 
  
func main() { 
  
    // Inizializzazione valori 
    res1 := value_1("w3codebox") 
    res2 := value_2(234) 
  
    // Stampa risultati visualizzati
    fmt.Println("Risultato 1: ", res1.display()) 
    fmt.Println("Risultato 2: ", res2.display()) 
}

Output:

Risultato 1: oldtoolbag.com
Risultato 2: 532