Struct và interface
Go Pointers: & and *
Share a value instead of copying it, so a function can change the original.
Bạn sẽ học được gì
- & 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.
Những điểm quan trọng
- Go copies arguments by default.
- &number is the address of number.
- *pointer reads or changes the value there.
Ví dụ Go chạy được
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)
}
21
42
7 7 true
1
trueLuyện tập
Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.
Bạn học xong bài này chưa?
Đánh dấu đã học để theo dõi tiến độ của bạn.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
- Swap First and Last Exchange the first and last items of a list. Dễ
- Thao tác với danh sách liên kết Mô phỏng danh sách liên kết: thêm vào hai đầu, xóa ở đầu hoặc theo giá trị, và đảo ngược. Dễ