首頁 > 後端開發 > Golang > 為什麼需要指標接收器來從 Go 結構體中的切片中刪除元素?

為什麼需要指標接收器來從 Go 結構體中的切片中刪除元素?

DDD
發布: 2024-11-15 11:43:02
原創
822 人瀏覽過

Why Do I Need a Pointer Receiver to Remove Elements from a Slice within a Go Struct?

Removing Elements from a Slice within a Struct

In Go, modifying a receiver object within a method requires the usage of a pointer receiver. This is a technique used to pass a reference to the object, rather than a copy, allowing changes made within the method to be reflected in the original object.

Consider the following Guest struct:

1

2

3

4

5

6

type Guest struct {

    id        int

    name      string

    surname   string

    friends   []int

}

登入後複製

To remove an element from the "friends" slice, one might initially write the following code:

1

2

3

4

5

6

7

8

func (self Guest) removeFriend(id int) {

    for i, other := range self.friends {

        if other == id {

            self.friends = append(self.friends[:i], self.friends[i+1:]...)

            break

        }

    }

}

登入後複製

However, this code would fail to remove the element as expected because the "removeFriend" method uses a value receiver instead of a pointer receiver. As a result, the changes made to the "friends" slice in the method are not reflected on the original object.

To rectify this issue, the "removeFriend" method should be revised to use a pointer receiver:

1

2

3

func (self *Guest) removeFriend(id int) {

    // Same logic as before

}

登入後複製

By using a pointer receiver, the method now modifies the original object rather than a copy. As a result, the changes made to the "friends" slice within the method are successfully reflected on the original Guest object.

以上是為什麼需要指標接收器來從 Go 結構體中的切片中刪除元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板