// 为类型添加方法 type Integer int // 定义一个新类型Integer, 它与int类型相同 func (a Integer) Less(b Integer) bool { // 给Integer类型添加新方法 less, less 方法输入一个整数,返回布尔值 return a < b // 当前整数a调用less方法要传入一个整数b, 如果a<b,返回true }
如果我们想在方法中修改对象,这种时候必须就要用到指针
func (a *Integer) Add (b Integer) { *a += b } func main() { a := Integer(10) a.Add(5) fmt.Println("a is : ", a) }
b = a b.Modyfy() // 如果a的值收到影响则a为引用类型,否则为值类型
值类型的数据:
// 数组想表达引用 var a = [3]int{1,2,3} var b = &a b[1]++ fmt.Println(a, *b)
类似引用类型的数据:
定义矩阵类型
type Rect struct {。 // 定义矩形类型 x, y float64 width, height float64 } func (r *Rect) Area() float64{ //定义成员方法计算矩形面积 return r.width * r.height }
初始化Rect类型的实例
rect1 := new(Rect) rect2 := &Rect{} rect3 := &Rect{0, 0, 100, 200} rect4 := {width:100, height:200}
type Base struct { // 定义Base类 Name string } func (base *Base) Par() { // Base类实现Par方法和Run方法 fmt.Println("par in Base") } func (base *Base) Run() { fmt.Println("run in base") } type Foo struct { // Foo类继承Base类 Base } func (foo *Foo) Run() { // Foo类重写Run方法,先执行Base的Run方法在执行自己的代码 foo.Base.Run() fmt.Println("run in foo") } func main() { foo := new(Foo) // 实例化一个foo对象,该对象有继承自父类的Par方法和自己的Run方法 foo.Par() foo.Run() }
原文:https://www.cnblogs.com/zhangjian0092/p/12358209.html