GO Methods 中指针和引用

Fork Me On Github
zodream 编程技术 Go 2018年09月
go
                                         
package main

import (
    "fmt"
)

type Hub struct {
    width, height int
}

func (r Hub) size() int  {
    return r.width * r.height
}

func (r *Hub) bound() int  {
    return r.width * r.height
}

func (r Hub) setX(x int)  {
    r.width = x
}

func (r *Hub) setY(y int)  {
    r.height = y
}

func main()  {
    hub := Hub{width: 1, height: 2}

    fmt.Println(hub)
    fmt.Println(hub.size())
    fmt.Println(hub.bound())

    hub.setX(10)
    hub.setY(20)

    fmt.Println(hub)
    fmt.Println(hub.size())
    fmt.Println(hub.bound())
}
1234567891011121314151617181920212223242526272829303132333435363738394041

输出

       
{1 2}
2
2
{1 20}
20
20
1234567

struct 的方法中尽可能使用 指针 ,除非不希望方法中改变影响主体内容才使用引用

引用实际上是复制主体,会花费相对较多的系统开销(内存和时间)

在方法中改变参数会改变指针主体参数,不改变引用主体参数

点击查看全文
0 305 0