Golang 结构体中的promoted方法
在Go结构中,promoted方法的工作就像 promoted字段 一样。 我们在嵌套结构中使用这个概念,一个结构是另一个结构中的一个字段,只需在另一个结构中加入该结构的名称,它就会像嵌套结构中的匿名字段一样表现。而该结构的方法(除嵌套结构外)是嵌套结构的一部分,这种类型的方法被称为提示方法。或者换句话说,被提示的方法是那些由子结构实现的方法,并且可以被父结构访问。
重要的一点是
- 如果子结构和父结构包含一个名称相同但接收者类型不同的方法,那么这两个方法在父结构中都可以使用,如例2所示。这里子结构和父结构都包含相同名称的方法。
- 如果子结构包含两个同名同姓的方法,那么这些方法在父结构中是不能被promoted的,如果你试图这样做,那么编译器会给出一个错误。
例1 :
// Golang program to illustrate the
// concept of the promoted methods
package main
import "fmt"
// Structure
type details struct {
// Fields of the
// details structure
name string
age int
gender string
psalary int
}
// Nested structure
type employee struct {
post string
eid int
details
}
// Method
func (d details) promotmethod(tsalary int) int {
return d.psalary * tsalary
}
func main() {
// Initializing the fields of
// the employee structure
values := employee{
post: "HR",
eid: 4567,
details: details{
name: "Sumit",
age: 28,
gender: "Male",
psalary: 890,
},
}
// Promoted fields of the
// employee structure
fmt.Println("Name: ", values.name)
fmt.Println("Age: ", values.age)
fmt.Println("Gender: ", values.gender)
fmt.Println("Per day salary: ", values.psalary)
// Promoted method of the
// employee structure
fmt.Println("Total Salary: ", values.promotmethod(30))
// Normal fields of
// the employee structure
fmt.Println("Post: ", values.post)
fmt.Println("Employee id: ", values.eid)
}
输出
Name: Sumit
Age: 28
Gender: Male
Per day salary: 890
Total Salary: 26700
Post: HR
Employee id: 4567
例2 :
// Golang program to illustrate the
// concept of the promoted methods
package main
import "fmt"
// Structure
type details struct {
// Fields of the
// details structure
name string
age int
gender string
psalary int
}
// Method 1
func (e employee) promotmethod(tarticle int) int {
return e.particle * tarticle
}
// Nested structure
type employee struct {
post string
particle int
eid int
details
}
// Method 2
func (d details) promotmethod(tsalary int) int {
return d.psalary * tsalary
}
// Main method
func main() {
// Initializing the fields of
// the employee structure
values := employee{
post: "HR",
eid: 4567,
particle: 5,
details: details{
name: "Sumit",
age: 28,
gender: "Male",
psalary: 890,
},
}
// Promoted fields of
// the employee structure
fmt.Println("Name: ", values.name)
fmt.Println("Age: ", values.age)
fmt.Println("Gender: ", values.gender)
fmt.Println("Per day salary: ", values.psalary)
// Promoted method of
// the employee structure
fmt.Println("Total Salary: ", values.promotmethod(30))
// Normal fields of
// the employee structure
fmt.Println("Post: ", values.post)
fmt.Println("Employee id: ", values.eid)
fmt.Println("Total Articles: ", values.promotmethod(30))
}
输出
Name: Sumit
Age: 28
Gender: Male
Per day salary: 890
Total Salary: 150
Post: HR
Employee id: 4567
Total Articles: 150