方法
方法的语句
package main
import "fmt"
type InitStruct struct {
name string
gender string
}
func (s InitStruct) displayMethod() {
fmt.Println(s.name)
fmt.Println(s.gender)
}
func main() {
method := InitStruct{
name: "Joker Even",
gender: "Man",
}
method.displayMethod()
}
定义相同的方法
package main
import (
"fmt"
"math"
)
type round struct {
radius float64
}
type square struct {
width float64
height float64
}
func (r round) area() float64 {
return r.radius * r.radius * math.Pi
}
func (s square) area() float64 {
return s.width * s.height
}
func main() {
r1 := round{5}
s1 := square{3, 4}
fmt.Println(r1.area())
fmt.Println(s1.area())
}
方法和函数
package main
import (
"fmt"
)
type Employee struct {
name string
salary int
currency string
}
func displaySalary(e Employee) {
fmt.Printf("Salary of %s is %s%d", e.name, e.currency, e.salary)
}
func main() {
emp1 := Employee{
name: "Sam Adolf",
salary: 5000,
currency: "$",
}
displaySalary(emp1)
}
变量作用域
package main
import (
"fmt"
)
type Rectangle struct {
width, height int
}
func (r *Rectangle) setVal() {
r.height = 20
}
func main() {
p := Rectangle{1, 2}
s := p
p.setVal()
fmt.Println(p.height, s.height)
}
结果 20, 2
没有* 结果 2, 2
继承中的方法
方法继承
package main
import "fmt"
type Person struct {
name string
gender string
}
type Programmer struct {
Person
wages float64
}
type FreeLancer struct {
Person
wages float64
}
func (p *Person) DefinedMethod(){
fmt.Println("This is Person'S Message:", p.name, p.gender)
}
func main() {
var pro = Programmer{Person{"Joker Even", "Man"}, 30000000}
var fre = FreeLancer{Person{"Joker Even", "Man"}, 300000000}
pro.DefinedMethod()
fre.DefinedMethod()
}
方法(method)的继承
package main
import "fmt"
type Person struct {
name string
gender string
}
type Programmer struct {
Person
wages float64
}
type FreeLancer struct {
Person
wages float64
}
func (p *Person) DefinedMethod() {
fmt.Println("This is Person'S Message:", p.name, p.gender)
}
func (f *FreeLancer) MethodRewrite() {
fmt.Println("对DefinedMethod的方法进行重写", "My Name Is", f.name, "I am A", f.gender, "I have", f.wages, "Money")
}
func main() {
var pro = Programmer{Person{"Joker Even", "Man"}, 30000000}
var fre = FreeLancer{Person{"Joker Even", "Man"}, 300000000}
pro.DefinedMethod()
fre.DefinedMethod()
fre.MethodRewrite()
}