Struct และ Interface

Go Pointers: & and *

Share a value instead of copying it, so a function can change the original.

  • ระดับกลาง
  • อ่าน 4 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • & takes an address
  • * follows a pointer
  • nil pointers
Passing 21 to a function
double(number)
  • gets a copy
  • number stays 21
doubleInPlace(&number)
  • gets the address
  • number becomes 42

An address instead of a copy

Go copies values when it passes them to a function. A pointer holds the address of a value, so a function that receives a pointer can change the original.

double changes only its own copy, so number stays 21. &number gives the address, and *value reads or changes what is stored there. Go follows a pointer to a struct for you, so counter.Count works. A pointer that points to nothing is nil.

ประเด็นสำคัญ

  1. Go copies arguments by default.
  2. &number is the address of number.
  3. *pointer reads or changes the value there.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
main.go
package main

import "fmt"

func double(value int) {
	value *= 2 // changes only the copy
}

func doubleInPlace(value *int) {
	*value *= 2 // changes the original through the pointer
}

type Counter struct{ Count int }

func main() {
	number := 21
	double(number)
	fmt.Println(number)

	doubleInPlace(&number)
	fmt.Println(number)

	pointer := &number
	*pointer = 7
	fmt.Println(number, *pointer, pointer == &number)

	counter := &Counter{}
	counter.Count++ // Go follows the pointer for you
	fmt.Println(counter.Count)

	var missing *Counter
	fmt.Println(missing == nil)
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
21
42
7 7 true
1
true

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Interfaces →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด