Golang 筆記
  • Introduction
  • 安裝Golang
    • 本地編譯與安裝第三方套件
    • 第一個 GO 程式
    • export 與 import
    • 使用 go mod
  • 基本工具
  • DataBase操作
    • MySQL
    • 使用 ORM
    • MongoDB
  • 基本語法
    • Variable
    • BSON
    • JSON
    • 時間相關
    • Interface
    • Error
    • 型別
    • 字串
    • defer
    • panic, recover
    • Channel 與Goroutine
      • 讀寫鎖
      • for select 與 for range
      • UnBuffered channel 與 Buffered channel
    • Function
    • pointer
    • regExp
    • fmt
    • Make vs New
    • struct
    • Array, Slice 陣列
    • map
  • 核心模組
    • Reflect
    • File
    • Signal
    • BuiltIn
    • Sync
    • IO
    • Sort
    • http
    • crypto
    • context
  • 第三方模組
    • Dom Parser
    • gin 框架
    • Websocket
    • Iris框架
      • 讀取 Body 資料
      • 相關範例
    • Fiber 框架
    • 自動重啟 server 工具
    • go-jwt
  • 測試
  • 原始碼解析
  • 常見問題
    • 資料存取不正確
    • Data races
Powered by GitBook
On this page
  • 傳值與傳址時機
  • 如果有 struct 傳入 func 建議都用指標
  • Unsafe.pointer

Was this helpful?

  1. 基本語法

pointer

PreviousFunctionNextregExp

Last updated 5 years ago

Was this helpful?

跟 c 語言的指標相同。

至於何時func 的參數要用pointer可參考:

傳值與傳址時機

假設我們今天有範例如下,想改變他的年紀

package main

import "fmt"

type User struct {
	Name string
	Age  int
}

func (c User) GetAge() {
	fmt.Println("Age:", c.Age)
}

func UpdateAge(c User, Age int) {
	c.Age = Age
}

func main() {
	c := User{"age", 20}
	c.GetAge()
	UpdateAge(c, 21)
	c.GetAge()
}

但結果都是Age: 20 Age: 20

所以我們要用傳指標的方式,才會真正改變到原本的物件

package main

import "fmt"

type User struct {
	Name string
	Age  int
}

func (c User) GetAge() {
	fmt.Println("Age:", c.Age)
}

func UpdateAge(c *User, Age int) {
	c.Age = Age
}

func main() {
	c := User{"age", 20}
	c.GetAge()
	UpdateAge(&c, 21)
	c.GetAge()
}

在 UpdateAge 第一個參數改為傳指標

如果有 struct 傳入 func 建議都用指標

因為耗費資源少。

Unsafe.pointer

https://flaviocopes.com/golang-methods-receivers/
https://golang.org/doc/faq#different_method_sets
http://tsunghao.github.io/post/2015/02/manipulating-pointers-in-golang/