方法
结构体方法
package main
import "fmt"
type Person struct {
name string
}
func (p Person) eat() {
fmt.Println("eat", p.name)
}
func (p Person) sleep() {
fmt.Println("sleep", p.name)
}
type Customer struct {
name string
pwd string
}
func (c Customer) login(name string, pwd string) bool {
fmt.Println(c.name, c.pwd)
if name == c.name && pwd == c.pwd {
return true
} else {
return false
}
}
func main() {
var c1 = Customer{
name: "tom",
pwd: "123",
}
r := c1.login("tom1", "123")
fmt.Println(r)
}
方法接收者类型
值类型结构体和指针类型结构体
demo1
package main
import "fmt"
type Person struct {
name string
}
func main() {
p1 := Person{
name: "tom",
}
fmt.Println(p1)
p2 := &Person{
name: "tom",
}
fmt.Printf("%v", p2)
}
demo2
package main
import "fmt"
type Person struct {
name string
}
func f1(p Person) {
p.name = "tom"
}
func f2(p *Person) {
p.name = "lisi"
}
func main() {
p := Person{
name: "name",
}
p2 := &Person{
name: "tom",
}
fmt.Println(p)
fmt.Println("调用值类型方法")
f1(p)
fmt.Println(p)
fmt.Println("调用指针类型方法")
f2(p2)
fmt.Println(*p2)
}
demo3
package main
import "fmt"
type Person struct {
name string
}
func (p Person) f3() {
p.name = "f3"
}
func (p *Person) f4() {
p.name = "f4"
}
func main() {
p := Person{
name: "name",
}
p2 := &Person{
name: "tom",
}
fmt.Println(p)
fmt.Println("调用值类型方法")
p.f3()
fmt.Println(p)
fmt.Println("调用指针类型方法")
p2.f4()
fmt.Println(*p2)
}