Go语言的面向对象编程

Go语言实现面向对象封装,代码如下:

package main

import (
	"fmt"
)

type Person struct {
	Name   string
	Gender string
	Age    int
}

func (p *Person) say(sentence string) {
	fmt.Print(p.Name, " says ", sentence, "\n")
}
func (p *Person) getAge() int {
	return p.Age
}
func main() {
	person1 := &Person{Name: "Tom", Gender: "male", Age: 25}
	person1.say("Hello!")
	person1.Name = "Jerry"
	person1.say("Hello!")
}

运行结果如下:

Tom says Hello!
Jerry says Hello!

改变成员变量的值,代码如下:

package main

import (
	"fmt"
)

type AA struct {
	B int
	C int
}

func (p *AA) Change() {
	p.B = 1
	p.C = 2
}
func main() {
	var a AA
	a.B = 10
	a.C = 20
	fmt.Printf("%v\n", a)
	a.Change()
	fmt.Printf("%v\n", a)
}

运行结果如下:

{10 20}
{1 2}

上一篇:[极客大挑战 2019]HardSQL


下一篇:数据库重组、重构