• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
留白
世人慌慌张张,不过图碎银几两
博客园    首页    新随笔       管理    订阅  订阅
go tour --函数,方法值参数与指针参数区别

函数

值参数是值传递

package main

import (
	"fmt"
)

type Vertex struct {
	X, Y float64
}

func update(v Vertex){
	v.X = 2
	v.Y = 2
}

func main() {
	v := Vertex{3, 4}
	update(v)
	fmt.Println(v)
}
// {3 4}

指针参数是引用传递

package main

import (
	"fmt"
)

type Vertex struct {
	X, Y float64
}

func update(v *Vertex){
	v.X = 2
	v.Y = 2
}

func main() {
	v := Vertex{3, 4}
	update(&v)
        // update(v)  报错:cannot use v (type Vertex) as type *Vertex in argument to update
        // 指针参数只能传指针
	fmt.Println(v)
}
// {2 2}

方法

与函数规则相同
唯一区别,值可以调用指针方法,指针也可以调用值方法

package main

import (
	"fmt"
)

type Vertex struct {
	X, Y float64
}

func (v *Vertex) update(){
	v.X = 2
	v.Y = 2
}

func main() {
	v := Vertex{3, 4}
	v.update()  // go 会将 v.update() 解释为 (&v).update()
	fmt.Println(v)
}

// {2 2}
package main

import (
	"fmt"
)

type Vertex struct {
	X, Y float64
}

func (v Vertex) update(){
	v.X = 2
	v.Y = 2
}

func main() {
	v := Vertex{3, 4}
	(&v).update() // GO 会自动做一次(*(&v)).update()
	fmt.Println(v)
}
// {3 4}
posted on 2020-07-17 11:23  留白s  阅读(172)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3